我有一个班级:
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
前面PictureBox
关键字的使用是什么,而不是省略关键字?
答案 0 :(得分:4)
此类包含扩展方法。
this
关键字表示该方法是扩展名。因此,示例中的方法ToCartesian
扩展了PictureBox
类,以便您可以编写:
PictureBox pb = new PictureBox();
Point p = pb.ToCartesian(oldPoint);
有关扩展方法的详细信息,请参阅MSDN上的文档:https://msdn.microsoft.com/en-us/library/bb383977.aspx
答案 1 :(得分:3)
扩展方法像实例方法一样被调用,但实际上是一个静态方法。实例指针“this”是一个参数。
和: 您必须在希望调用方法的相应参数之前指定this-keyword。
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);
}
}
请参阅http://www.dotnetperls.com/extension了解详情。
**编辑:通过评论
一次又一次尝试以下示例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);
}
}
}