C#中参数内部使用“this”关键字的用法

5

我有一个类:

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);
    }
}

我的问题是,在PictureBox前面使用this关键字有什么用处,与不使用关键字有什么区别?

请查看编辑内容。希望能对您有所帮助。 - Masoud Mohammadi
2个回答

7

扩展方法被称为实例方法,但实际上是静态方法。实例指针“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);
    }
}

请查看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);
        }
    }
}

6

这个类包含扩展方法。

this 关键字表示该方法是一个扩展方法。因此,在您的示例中,ToCartesian 方法扩展了 PictureBox 类,以便您可以编写以下代码:

PictureBox pb = new PictureBox();
Point p = pb.ToCartesian(oldPoint);

有关扩展方法的更多信息,请参阅MSDN上的文档:https://msdn.microsoft.com/zh-cn/library/bb383977.aspx


这是一个正确的答案,不需要给它点踩! - Roy Dictus
有的。你最初的回答是“这个类包含扩展方法。”其实并不需要那么简短,你可以更详细地解释一下。 - Patrick Hofman
1
必须有耐心,年轻的Jedi。-- 尤达 - Roy Dictus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接