开发者

Why is it allowed to set a property that doesn't set anything in C#?

I'v开发者_开发问答e been reviewing the PRISM toolkit and I find many examples where they declare a public property with empty getters/setters yet they can still set the property of the instantiated class. How/why is this possible?

    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;


This is a new feature in C# 3.0.

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

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.


They're using C# auto properties. It's a convenience whereby the compiler generates the backing field for you. private set means that the property is read-only from outside the class. So, if sp.View = someView; is being used outside of the class then it will result in a compiler error.


Decompiling your ShellPresenter with the 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;
    }
  }
}


What you posted is not allowed unless the object is being set within the class itself. Here's a code sample of what is and is not allowed.

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


C# compiler generates backend field for you. This syntax was introduced for anonymous types support (like new { A = 1, B = "foo" } )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜