Can you add extension methods to a struct?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Yes, you can add extension methods on structs. As per the definition of extension method, you can easily achieve it. Below is example of extension method on int
It is possible to add extension methods to structures, but there is an important caveat. Normal struct methods methods accept
this
as aref
parameter, but C# will not allow the definition of extension methods which do so. While struct methods which mutatethis
can be somewhat dangerous (since the compiler will allow struct methods to be invoked on read-only structures, but passthis
by value), they can also at times be useful if one is careful to ensure that they are only used in appropriate contexts.Incidentally, vb.net does allow extension methods to accept
this
as aByRef
parameter, whether it is a class, struct, or an unknown-category generic. This can be helpful in some cases where interfaces may be implemented by structures. For example, if one attempts to invoke on a variable of typeList<string>.Enumerator
an extension method which takes athis
parameter of typeIEnumerator<string>
, or takes by value athis
parameter of a generic constrained toIEnumerator<string>
, and if the method tries to advance the enumerator, any advancement will be undone when the method returns. An extension method which takes a constrained generic by reference, however, (possible in vb.net) will behave as it should.For future Googlers (and Bingers), here's some code to extend a struct. This example turns the value into a
double
type.After this you can use
ToDouble()
like you useToString()
. Be careful on conversion items like overflows.Yes, you can define an extension method on a struct/value type. However, they do not have the same behavior as extension methods on reference types.
For example, the GetA() extension method in the following C# code receives a copy of the struct, not a reference to the struct. This means that a C# extension method on a struct can't modify the original struct contents.
In order to modify the struct contents, the struct paramater needs to be declared as "ref". However, "this ref" is not allowed in C#. The best we can do is a static non-extension method like:
In VB.NET, you can create this as a ByRef struct extension method, so it could modify the original struct: