Extension methods on a struct

前端 未结 4 439
野趣味
野趣味 2020-12-17 07:46

Can you add extension methods to a struct?

4条回答
  •  误落风尘
    2020-12-17 08:08

    It is possible to add extension methods to structures, but there is an important caveat. Normal struct methods methods accept this as a ref parameter, but C# will not allow the definition of extension methods which do so. While struct methods which mutate this can be somewhat dangerous (since the compiler will allow struct methods to be invoked on read-only structures, but pass this 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 a ByRef 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 type List.Enumerator an extension method which takes a this parameter of type IEnumerator, or takes by value a this parameter of a generic constrained to IEnumerator, 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.

提交回复
热议问题