代码之家  ›  专栏  ›  技术社区  ›  user134363

为什么允许设置一个不在C#中设置任何内容的属性?

  •  3
  • user134363  · 技术社区  · 16 年前

    我已经回顾了PRISM工具箱,并且发现了许多示例,在这些示例中,它们声明了一个带有空getter/setter的公共属性,但仍然可以设置实例化类的属性。这怎么可能?

        public class ShellPresenter
        {
            public ShellPresenter(IShellView view)
            {
                View = view;
    
            }
    
            public IShellView View { get; private set; }
        }
    
    //calling code
    ShellPresenter sp = new ShellPresenter();
    
    //Why is this allowed?
        sp.View = someView;
    
    5 回复  |  直到 16 年前
        1
  •  8
  •   Rodrick Chapman    16 年前

    private set 表示该属性是类外部的只读属性。所以,如果 sp.View = someView; 在类之外使用,则会导致编译器错误。

        3
  •  0
  •   statenjason    16 年前

    使用 Red Gate .NET Reflector

    public class ShellPresenter
    {
    // Fields
    [CompilerGenerated]
    private IShellView <View>k__BackingField;
    
    // Methods
    public ShellPresenter(IShellView view)
    {
        this.View = view;
    }
    
    // Properties
    public IShellView View
    {
        [CompilerGenerated]
        get
        {
            return this.<View>k__BackingField;
        }
        [CompilerGenerated]
        private set
        {
            this.<View>k__BackingField = value;
        }
      }
    }
    
        4
  •  0
  •   P.Brian.Mackey    16 年前

       public interface IShellView
        {
    
        }
        public class View:IShellView
        {
        }
    
        //public class SomeOtherClass
        //{
        //    static void Main()
        //    {
        //        IShellView someView = new View();
        //        //calling code 
        //        ShellPresenter sp = new ShellPresenter();
    
        //        //Why is this allowed? 
        //        sp.View = someView;//setting a private set outside the ShellPresenter class is NOT allowed.
        //    }
        //}
    
        public class ShellPresenter
        {
            public ShellPresenter()
            {
            }
            public ShellPresenter(IShellView view)
            {
                View = view;
    
            }
            static void Main()
            {
                IShellView someView = new View();
                //calling code 
                ShellPresenter sp = new ShellPresenter();
    
                //Why is this allowed? 
                sp.View = someView;//because now its within the class
            }
            public IShellView View { get; private set; }
        } 
    
        5
  •  -1
  •   STO    16 年前

    C编译器为您生成后端字段。这种语法是为支持匿名类型而引入的(比如 new { A = 1, B = "foo" } )