Can C# extension methods access private variables?

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

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

7条回答
  •  难免孤独
    2021-02-01 12:21

    No:

    public class Foo
    {
        private string bar;
    }
    
    public static class FooExtensions
    {
        public static void Test(this Foo foo)
        {
            // Compile error here: Foo.bar is inaccessible due to its protection level  
            var bar = foo.bar;
        }
    }
    

提交回复
热议问题