简体   繁体   English

.NET中值类型的方法

[英]Methods on value types in .NET

I'm reading a "CLR via C#" by Jeffrey Richter and he suggests never define methods in a value type that are intended to change it's behavior cause value types should be immutable (because of boxing/unboxing expenses and sometimes unpredictable behavior). 我正在阅读Jeffrey Richter的“CLR via C#”,他建议永远不要在值类型中定义旨在改变它的行为的方法,因为值类型应该是不可变的(因为装箱/拆箱费用,有时候是不可预测的行为)。

So, we can define methods in our custom value type only for displaying it's state? 那么,我们可以在自定义值类型中定义方法,仅用于显示它的状态?

Can You give any other examples where the ability to define methods within a Struct is needed? 您能否提供其他需要在Struct定义方法的能力的示例?

The best example I can think of is the DateTime struct. 我能想到的最好的例子是DateTime结构。

All instance methods on the type are designed to create a new DateTime by manipulating the current one (eg AddMinutes ) or get additional information from the current DateTime (eg IsDaylightSavingsTime ). 该类型上的所有实例方法都旨在通过操纵当前的DateTime (例如AddMinutes )或从当前DateTime获取其他信息(例如IsDaylightSavingsTime )来创建新的DateTime It also has a variety of static methods for creating a new instances from various inputs, (eg FromBinary ) or generally manipulating DateTime values (eg Compare ) 它还有各种静态方法,用于从各种输入创建新实例(例如FromBinary )或通常操作DateTime值(例如, Compare

No method can actually modify the current instance. 没有方法可以实际修改当前实例。

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

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