本文介绍了为什么要对原始值使用表达式主体属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
表达式实体属性与直接属性声明的优缺点是什么?例如,使用;
What are the pros and cons of expression-bodied properties vs straight property declarations? For example, is there any advantage to using;
public string Foo => "Bar"
对比简单
public string Foo = "Bar"
我的理解是 =>
用于值来自方法(如 lambda 函数)时.如果值是像字符串或整数这样的原始值,为什么有人会为此使用表达式主体属性?
My understanding was the =>
is used when the value comes from a method, like a lambda function. If the value is a primitive like a string or int, why would anyone use an expression-bodied property for that?
推荐答案
这两行代码有不少区别:
There are quite a few differences between those two lines of code:
- 第一个是属性,第二个是字段.例如,你不能
ref
第一个Foo
. - 属性每次都会被评估并返回一个新对象,即使该对象是相同的字符串文字.变量被评估一次,使用时它只是加载.(请注意,编写 #1 的更好方法是
public string Foo { get; } = "Bar";
,它也将被初始化一次,然后返回相同的值. - 第一个是只读的(它只是一个 getter),而第二个是一个可变变量,你可以写入它.更接近的等价物是
public readonly string Foo = "Bar";
或者更好的public static readonly string Foo = "Bar";
- The first one is a property, the second is a field. For example, you cannot
ref
the firstFoo
. - The property gets evaluated and returns a new object every time, even if the object is the same string literal. The variable is evaluated once and when used it's just loaded. (Note that a better way to write #1 is
public string Foo { get; } = "Bar";
which would also be initialized once and then return the same value). - The first one is read-only (it's a getter only), while the second one is a mutable variable, you can write into it. A closer equivalent would be
public readonly string Foo = "Bar";
or even betterpublic static readonly string Foo = "Bar";
这篇关于为什么要对原始值使用表达式主体属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!