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)
    {
        return new Point(p.X, box.Height - p.Y);
    }
}

我的问题是 PictureBox 前面的 this 关键字有什么用,而不是省略关键字?

最佳答案

扩展方法的调用方式类似于实例方法,但实际上是静态方法。实例指针“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);
    }
}

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

关于c# - 在参数 c# 中使用 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28360816/

相关文章:

c# - nHibernate - 定义类(和表)时何时使用对象

c# - HttpWebRequest 在第二次调用 Web 服务器时超时

javascript - 在 javascript 类中调用类方法

java - 用这个。或 super 。当调用父类(super class)和子类中存在的方法时

javascript - 如何在 JavaScript 中使用 "this"

javascript - 如何在回调中访问正确的“this”?

c# - Visual Studio 不更新构建

c# - 使用 Sitecore Webforms For Marketers 生成摘要报告

c# - 在 C# 中加密文件名而不在结果字符串中包含不可用的字符

java - 对象方法调用可以和对象实例化同时进行吗?