Can C# extension methods access private variables?

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

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

7条回答
  •  有刺的猬
    2021-02-01 12:14

    No it cannot.

    However, you will be interested to know that the other answers are incorrect in saying that normal static methods cannot access private fields. A static method can access private non-static member fields in its own class. The following code is perfectly valid and shows a static method accessing a private field:

    public class Foo
    {
        private bool _field;
    
        public static bool GetField(Foo foo)
        {
            return foo._field;
        }
    }
    

    Now... back to your question. You might think that an extension method should be able to do the same thing, given the (non-existent) "equivalence" to static methods that other answers claim exists. However, you cannot declare extension methods inside a nested class. So if you try to do the following:

    public class Foo
    {
        private bool _field;
    
        public static class Extensions
        {
            public static bool GetField(this Foo foo)
            {
                return foo._field;
            }
        }
    }
    

    You will get a compile error saying

    Extension method must be defined in a top level static class; Extensions is a nested class

    Note that, interestingly enough, removing the this keyword causes the code to compile fine. The reasons for this are discussed here:

    1. Why are extension methods only allowed in non-nested, non-generic static class?
    2. Why not allow Extension method definition in nested class?

提交回复
热议问题