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

时间:2010-07-02 19:41:34

标签: c# properties

我一直在审查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 个答案:

答案 0 :(得分:11)

这是C#3.0中的一项新功能。

http://msdn.microsoft.com/en-us/library/bb384054.aspx

  

在C#3.0及更高版本中,当属性访问器中不需要其他逻辑时,自动实现的属性使属性声明更简洁。

答案 1 :(得分:8)

他们正在使用C#自动属性。这是一种方便,编译器为您生成支持字段。 private set表示该属性在类外部是只读的。因此,如果在类之外使用sp.View = someView;,则会导致编译器错误。

答案 2 :(得分:0)

使用Red Gate .NET Reflector

反编译ShellPresenter
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;
    }
  }
}

答案 3 :(得分:0)

除非在类本身内设置对象,否则不允许发布的内容。这是一个代码样本,包括什么是不允许的。

   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; }
    } 

答案 4 :(得分:-1)

C#编译器为您生成后端字段。此语法是为匿名类型支持(如new { A = 1, B = "foo" }

引入的