C# expression body with {get;} vs without [duplicate]

空扰寡人 提交于 2020-01-30 08:50:05

问题


Since I don't know the term that applies to this, I am not sure what to search for existing comments on this.

I recently wasted a ton of time with an expression body similar to:

public SomeListViewModel SearchSomeModel => new ShowSomeViewModel{...};

When I tried to set values such as:
SearchSomeModel.Property = 12345;

It acted like all was good. But the actual value never changed. When I instead inserted a {get;} as in:

public SomeListViewModel SearchSomeModel {get;} =  new ShowSomeViewModel{...};

It worked correctly.

The funny thing is that if this starts out as a normal get (with a get {return ..} then ReSharper(?) offers to convert it to the first version.

Anyway, I want to understand the difference between the two (no, not at a CLR level) but just to a) know how to refer to each in it's proper terms and b) why one works and the other just pretends to work.

Thanks!


回答1:


The first line of code -

public SomeListViewModel SearchSomeModel => new ShowSomeViewModel{...};

means that it will create a new instance of ShowSomeViewModel every time that you try to get it.
It is the equivalent of:

public SomeListViewModel SearchSomeModel {
    get {return new ShowSomeViewModel{...};}
}

On the other hand the

public SomeListViewModel SearchSomeModel {get;} =  new ShowSomeViewModel{...};

means you are setting a default value.




回答2:


The code

public SomeListViewModel SearchSomeModel {get;} =  new ShowSomeViewModel{...};

gets translated to the equivalent of

private SomeListViewModel _searchSomeModel  =  new ShowSomeViewModel{...};
public SomeListViewModel SearchSomeModel 
{
    get
    {
        return _searchSomeModel;
    }
}

the code

public SomeListViewModel SearchSomeModel => new ShowSomeViewModel{...};

gets translated to the equivlant of

public SomeListViewModel SearchSomeModel 
{
    get
    {
        return new ShowSomeViewModel{...};
    }
}

When using the 2nd form every time you call the property you are getting a new instance of ShowSomeViewModel, when using the first form you get the same object back each call.

The reason the 2nd form did not work was you where updating the value on the old instance but when you called the property a 2nd time to check the value you where getting a new instance of the view model that did not have your changes.



来源:https://stackoverflow.com/questions/42907686/c-sharp-expression-body-with-get-vs-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!