带有{get;}的C#表达式主体与没有 [英] C# expression body with {get;} vs without

查看:111
本文介绍了带有{get;}的C#表达式主体与没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我不知道适用于此的术语,因此我不确定要搜索关于此内容的现有评论.

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

当我尝试设置以下值时:
SearchSomeModel.Property = 12345;

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

一切都很好.但是实际价值从未改变.当我改为插入{get;}时,如下所示:

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

它正常工作.

有趣的是,如果此操作以正常的get(以get {return ..}开头),那么ReSharper(?)会提供将其转换为第一个版本的功能.

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.

无论如何,我想了解两者之间的区别(不,不是在CLR级别上),而是要:a)知道如何用适当的术语来指称每个; b)为什么一个可行而另一个却假装工作.

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.

谢谢!

推荐答案

第一行代码-

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

表示每次尝试时都会创建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{...};}
}

另一方面

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

表示您正在设置默认值.

means you are setting a default value.

这篇关于带有{get;}的C#表达式主体与没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆