简体   繁体   English

具有getter和setter的值类型仍然是值类型吗?

[英]Is a value-type with getters and setters still a value-type?

In C#, if I have the following code: 在C#中,如果我有以下代码:

public int VarName { get; set; }
  1. Will VarName still be a value type? VarName仍然是值类型吗?

  2. Will any boxing or unboxing occur? 会发生装箱或拆箱吗?

  3. Is there any overhead for storing references relating to get / set? 存储与get / set有关的引用是否有开销?

Yes, it will still be a value type. 是的,它仍然是值类型。

No, there won't be any boxing or unboxing (since you're not treating it as an Object). 不,不会进行装箱或拆箱(因为您没有将其视为对象)。

And no, there is no overhead since you're not storing references relating to get/set. 不,没有开销,因为您没有存储与get / set有关的引用。 It simply stores the int in a compiler generated backing field. 它只是将int存储在编译器生成的后备字段中。

The getter and setter are actually methods and not fields. getter和setter实际上是方法,而不是字段。 They will set a backing field of type int (that is a value type) and return that same backing field. 他们将设置int类型的后备字段(即值类型),并返回相同的后备字段。

However the compiler (at least the Microsoft one) will optimize this code, and make the method call to the getter and setter inline, so that the performance between the property, and using a public field is the same. 但是,编译器(至少是Microsoft编译器)将优化此代码,并内联调用getter和setter的方法,以使属性与使用公共字段之间的性能相同。

It's always preferred to use a property instead of a public variable in a class. 始终首选在类中使用属​​性而不是公共变量。 A good reason for this is that if you suddenly needs to make some validation when setting the variable, you can do so without changing any code calling the class, and it also makes it possible to only have the getter public, so that any subscriber to your class can only get the value and not set it. 这样做的一个很好的理由是,如果您在设置变量时突然需要进行一些验证,则可以在不更改调用该类的任何代码的情况下进行验证,并且还可以仅将getter公开,以便任何订阅者您的班级只能获取该值,而不能设置它。

Will VarName still be a value type? VarName仍然是值类型吗?

Yes. 是。

Also will any boxing or unboxing occur? 还会进行装箱或拆箱吗?

No, because there's no conversion between a reference type and a value type. 不,因为在引用类型和值类型之间没有转换。

Is there any overhead for storing references relating to get / set? 存储与get / set有关的引用是否有开销?

No. The C# compiler automagically generates optimized get and set methods, which do nothing but retrieve and set, respectively, the value of a compiler generated variable. 否。C#编译器自动生成优化的get和set方法,这些方法除了分别检索和设置编译器生成的变量的值外,什么也不做。 It's generally better to expose variables as properties rather than public fields so that things like data binding work right, and just as a general best practice. 通常最好将变量公开为属性而不是公共字段,以使诸如数据绑定之类的事情正常工作,并作为一般的最佳实践。

是的,它会,但是,如果它是一个类的属性,它将继续堆放,并且也不会发生装箱和拆箱,直到您在代码中显式地进行装箱为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM