C# 此关键字在参数c中的用法#
我有一门课:C# 此关键字在参数c中的用法#,c#,this,C#,This,我有一门课: public static class PictureBoxExtensions { public static Point ToCartesian(this PictureBox box, Point p) { return new Point(p.X, p.Y - box.Height); } public static Point FromCartesian(this PictureBox box, Point p)
public static class PictureBoxExtensions
{
public static Point ToCartesian(this PictureBox box, Point p)
{
return new Point(p.X, p.Y - box.Height);
}
public static Point FromCartesian(this PictureBox box, Point p)
{
return new Point(p.X, box.Height - p.Y);
}
}
我的问题是
图片盒
前面的这个
关键字有什么用,而不是省略关键字 此类包含扩展方法
this
关键字表示该方法是一个扩展。因此,示例中的方法ToCartesian
扩展了PictureBox
类,因此您可以编写:
PictureBox pb = new PictureBox();
Point p = pb.ToCartesian(oldPoint);
有关扩展方法的更多信息,请参阅MSDN上的文档:扩展方法的调用类似于实例方法,但实际上是静态方法。实例指针“this”是一个参数 以及: 必须在调用该方法的适当参数之前指定this关键字
public static class ExtensionMethods
{
public static string UppercaseFirstLetter(this string value)
{
// Uppercase the first letter in the string this extension is called on.
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
class Program
{
static void Main()
{
// Use the string extension method on this value.
string value = "dot net perls";
value = value.UppercaseFirstLetter(); // Called like an instance method.
Console.WriteLine(value);
}
}
有关更多信息,请参阅
**编辑:反复尝试下面的示例并添加注释
pb.Location=pb.FromCartesian(new Point(20, 20));
看看结果**
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Size = new Size(200, 200);
pb.BackColor = Color.Aqua;
pb.Location=pb.FromCartesian(new Point(20, 20));
Controls.Add(pb);
}
}
public static class PictureBoxExtensions
{
public static Point ToCartesian(this PictureBox box, Point p)
{
return new Point(p.X, p.Y - box.Height);
}
public static Point FromCartesian(this PictureBox box, Point p)
{
return new Point(p.X, box.Height - p.Y);
}
}
}
这是一个正确的答案,没有必要投反对票!有。您最初的回答是“这个类包含扩展方法”。没有这个必要。你本可以轻松地多解释一点。耐心,你必须要有。-用Yodase编辑。我希望有帮助。