简体   繁体   中英

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).

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?

The best example I can think of is the DateTime struct.

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 ). 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 )

No method can actually modify the current instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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