在 C# 中访问成员时,“this”关键字是可选的吗?

发布于 2024-09-25 01:18:21 字数 190 浏览 7 评论 0原文

我注意到,如果类中有私有成员,则只需引用它的名称即可在类方法中访问它。您不需要说 this.memberName,只需 memberName 即可。那么 this 关键字在成员访问的上下文中是可选的吗?

我确实认为当您想要澄清范围时(当您有两个同名变量时)它很有用。访问会员时还有其他理由使用它吗?

I notice that if you have a private member in a class, you can access it in the class methods by just referring to it's name. You do not need to say this.memberName, just memberName works. So is the this keyword optional in the context of member access?

I do see it is useful when you want to clarify the scope - when you have 2 variables with the same name. Is there any other reason to use it when accessing members?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不甘平庸 2024-10-02 01:18:21

是的,它是可选的。唯一需要使用它的情况是当您有一个隐藏成员变量的局部变量,或者您想要引用 索引属性(也称为索引器)

Yes, it's optional. The only times you'd have to use it are when you have a local variable that hides a member variable, or you want to refer to an indexed property (aka indexer).

靑春怀旧 2024-10-02 01:18:21

您可以选择在实例成员(例如实例方法或属性)内的实例成员访问中使用 this,因为每当调用实例方法时,this(引用当前对象)都会被调用。自动作为不可见参数传入。

您不能在静态成员中使用 this 来访问实例成员...就像您不能使用 this.xthis.y (甚至如果 x 和 y 是实例成员,则来自静态方法或属性中的简单 x 和 y)。这是因为 this 在静态成员调用中未定义。静态成员属于整个类...它不知道 this 引用的是哪个实例。这是因为当你调用静态方法或属性时,调用的格式是ClassName.MethodName();,所以静态方法不知道this<是什么对象/code> 将引用。

this 也不是可选的(必须使用)作为扩展方法的参数列表中的第一个修饰符。事实上,this 是将静态方法标识为扩展方法的内容。现在,this 将第一个参数标识为扩展方法正在运行的实例。

    using System;



    class Class_name
    {


        static  string static_variable="static";

        string instance_variable="instance";


        static void Main()
        {

            Class_name object_name = new Class_name();

            Console.WriteLine("Printing out instance and static variables from within Main() body :");

            Console.WriteLine(object_name.instance_variable);
            Console.WriteLine(Class_name.static_variable);

            /* Note that we cannot say either of the following :

                    object_name.static_variable 
                    Class_name.instance_variable


            */

            Console.WriteLine();




            // now lets call the static and instance methods

            object_name.Instance_method(); // Now this is the key call which 
            // passes "this" as an invisible parameter 
            // to the Instance_method. "this" refers to  
            //  object_name


            Class_name.Static_method();//  "this" is NOT passed to Static_method() because now 
            // the call is made on Class_name ... so there is nothing
            // to be represented by "this"


            Console.ReadLine();

        }



        void Instance_method()
        { 

            // here we receive "this" as an invisible parameter referring 
            // to the object on which  Instance_method is called (i.e. object_name)...
            // ... see the Main() method for comments at the call site. 


            Console.Write("Instace method called ... " +
                            "prints out instance variable twice, with and without 'this': ");

            // the following two calls mean exactly the same.

            Console.Write(this.instance_variable);
            Console.WriteLine (instance_variable);



            // one little additional point is that static members are 
            // accessible from within instance members


            Console.WriteLine();

            Console.Write("static variables can also be accessed from within Instance_method: ");
            Console.WriteLine(static_variable);

            Console.WriteLine();
            Console.WriteLine();




        }


        static void Static_method()
        {

            // See the Main() method body for the call Class_name.Static_method()
            // Notice that this method is called on Class_name and not object_name
            // which means that there is no invisibly passed-in "this" parameter available
            // in this method. 

            // we can also not access the instance_variable in this method 
            // as instance variables are always part of some object. This method
            // is not called on any object, its called on Class_name.

            // Console.WriteLine(instance_variable); // Compiler error

            Console.WriteLine("Static method called ... prints out static variable: ");
            Console.WriteLine(static_variable);




        }






    }

You can optionally use this in instance member access from within an instance members like an instance method or property because whenever an instance method is called this (referring to the current object) is automatically passed in as an invisible parameter.

You cannot use this from within static members to access instance member... like you cannot use this.x or this.y (or even simple x and y) from within a static method or property if x and y are instance members. This is because this is undefined in a static member call. The static member belongs to the whole class... it has no idea which instance this is referring to. And that is due to the fact that when you call a static method or property , the call is of the format ClassName.MethodName(); So the static method does not know what object this will refer.

this is also not optional (it must be used) as the first modifier in the parameter list of an extension method. In fact this is what identifies a static method as an extension method. Here now this identifies the first parameter as the instance on which the extension method is working.

    using System;



    class Class_name
    {


        static  string static_variable="static";

        string instance_variable="instance";


        static void Main()
        {

            Class_name object_name = new Class_name();

            Console.WriteLine("Printing out instance and static variables from within Main() body :");

            Console.WriteLine(object_name.instance_variable);
            Console.WriteLine(Class_name.static_variable);

            /* Note that we cannot say either of the following :

                    object_name.static_variable 
                    Class_name.instance_variable


            */

            Console.WriteLine();




            // now lets call the static and instance methods

            object_name.Instance_method(); // Now this is the key call which 
            // passes "this" as an invisible parameter 
            // to the Instance_method. "this" refers to  
            //  object_name


            Class_name.Static_method();//  "this" is NOT passed to Static_method() because now 
            // the call is made on Class_name ... so there is nothing
            // to be represented by "this"


            Console.ReadLine();

        }



        void Instance_method()
        { 

            // here we receive "this" as an invisible parameter referring 
            // to the object on which  Instance_method is called (i.e. object_name)...
            // ... see the Main() method for comments at the call site. 


            Console.Write("Instace method called ... " +
                            "prints out instance variable twice, with and without 'this': ");

            // the following two calls mean exactly the same.

            Console.Write(this.instance_variable);
            Console.WriteLine (instance_variable);



            // one little additional point is that static members are 
            // accessible from within instance members


            Console.WriteLine();

            Console.Write("static variables can also be accessed from within Instance_method: ");
            Console.WriteLine(static_variable);

            Console.WriteLine();
            Console.WriteLine();




        }


        static void Static_method()
        {

            // See the Main() method body for the call Class_name.Static_method()
            // Notice that this method is called on Class_name and not object_name
            // which means that there is no invisibly passed-in "this" parameter available
            // in this method. 

            // we can also not access the instance_variable in this method 
            // as instance variables are always part of some object. This method
            // is not called on any object, its called on Class_name.

            // Console.WriteLine(instance_variable); // Compiler error

            Console.WriteLine("Static method called ... prints out static variable: ");
            Console.WriteLine(static_variable);




        }






    }
喜爱纠缠 2024-10-02 01:18:21

是的,“这个”是隐含的。有时它可以帮助清晰。而且调用方法也是需要的,需要引用当前类。

Yes, 'this' is implied. It can sometimes help for clarity. And it is also necessary for calling methods and need to reference the current class.

多像笑话 2024-10-02 01:18:21

当您呼叫当前班级的成员时,“this”几乎总是可选的。

然而,它还用于其他目的,例如将当前类实例作为参数传递或将属性、字段或变量设置为当前实例。

必须使用它来调用方法的唯一情况是调用扩展方法时:

class AClass {
    void CallIt() {
        Test();                     //not valid
        this.Test();                //valid 
    }
}
static class AnExtension {
    public static void Test(this AClass source) {

    }
}

"This" is almost always optional when you call members of current class.

However, it is used for other purposes, e.g. to pass the current class instance as a parameter or to set a property,field or variable to the current instance.

The only case where you must use it to call a method is when you call an extension method:

class AClass {
    void CallIt() {
        Test();                     //not valid
        this.Test();                //valid 
    }
}
static class AnExtension {
    public static void Test(this AClass source) {

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文