Extension methods on a struct

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

Can you add extension methods to a struct?

4条回答
  •  醉梦人生
    2020-12-17 08:31

    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.

    public static class TestStructExtensionMethods {
        public struct FooStruct {
            public int a;
        }
        public static int GetA(this FooStruct st) {
            return st.a;
        }
    }
    

    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:

    // this works, but is inefficient, because it copies the whole FooStruct
    // just to return a
    public static int GetA(ref FooStruct st) {
        return st.a;
    }
    

    In VB.NET, you can create this as a ByRef struct extension method, so it could modify the original struct:

    ' This is efficient, because it is handed a reference to the struct
     _ 
    Public Sub GetA(ByRef [me] As FooStruct) As Integer
        Return [me].a
    End Sub
    
    ' It is possible to change the struct fields, because we have a ref
     _ 
    Public Sub SetA(ByRef [me] As FooStruct, newval As Integer) 
        [me].a = newval
    End Sub
    

提交回复
热议问题