C# abstract struct

前端 未结 9 1913
闹比i
闹比i 2021-01-11 14:34

How can I achieve inheritance (or similar) with structs in C#? I know that an abstract struct isn\'t possible, but I need to achieve something similar.

I need it as

9条回答
  •  轮回少年
    2021-01-11 15:30

    Maybe you can use a "union" type:

    enum VertexType : byte { 
      Vertex,
      ColorVertex
    }
    
    [StructLayout(LayoutKind.Explicit)]
    struct Vertex {
    
      [FieldOffset(0)]
      public readonly VertexType Type;
    
      [FieldOffset(1)]
      public readonly int SizeInBytes;
    
      public Vertex(VertexType type /* other necessary parameters... */) {
        Type = type;
        // set default values for fields...
        switch (Type) {
          // set the fields for each type:
          case VertexType.ColorVertex: 
            SizeInBytes = (3 + 4) * 4; 
            // other fields ...
            break;
          default: 
            SizeInBytes = 2; // or whatever...
            // other fields ...
            break;
        }
      }
    
      // other fields with overlapping offsets for the different vertex types...
    
    }
    

    Just remember to make it immutable and to access only the fields that make sense for each type.

提交回复
热议问题