Can C# extension methods access private variables?

前端 未结 7 1126
借酒劲吻你
借酒劲吻你 2021-02-01 11:49

Is it possible to access an object\'s private variables using an extension method?

7条回答
  •  误落风尘
    2021-02-01 12:36

    No. You can do the same in an extension method as in a "normal" static method in some utility class.

    So this extension method

    public static void SomeMethod(this string s)
    {
        // do something with 's'
    }
    

    is equivalent to some static helper method like this (at least regarding what you can access):

    public static void SomeStringMethod(string s)
    {
        // do something with 's'
    }
    

    (Of course you could use some reflection in either method to access private members. But I guess that's not the point of this question.)

提交回复
热议问题