Generics with structs and fields
Hello I have a problem with generics, i'am creating a custom vertex structure for my game and i want to be abel to do this with generics so i can change my vertex type quickly.
th开发者_运维问答is is what it looks like right now:
public struct ETerrainVertex
{
public Vector3 Position;
public Vector3 Normal;
public Vector2 TextureCoordinate;
public static int SizeInBytes = (3 + 3 + 2) * 4;
public static VertexElement[] VertexElements = new VertexElement[]
{
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
};
}
And then I use it like this:
//I have to add a constraint to the T but an interface wont cut.
//where T : struct, thingThatAddsConstrainsPositionAndNormal
public sealed class EQuadNode<T> : IEclipse where T : struct
{
T foo;
foo.Position; //dont work
}
But since I use fields i cant simply create an interface and add it to the where restrictions as interfaces only can have properties.
So is there any way to do this?
You can create in interface for ETerrainVertex
if you use properties instead of fields:
public interface IVertex
{
public Vector3 Position {get;set;}
}
public struct ETerrainVertex : IVertex
{
public Vector3 Position {get;set;}
}
Don't worry about the performance impact of using properties, as there is none in this case IIRC.
If you want to use only ETerrainVertex
- you should not use generics and put the type explicitly. Using generics in such case is just meaningless because you won't be able to use any other type but ETerrainVertex
.
If you want to use another types - you should use inheritance. And because CLR don't allow you to inherit from structs - you should
specify an interface and encapsulate your fields into properties in your structure.
And next important thing - if you decide to use interface - it's possible that a lot of boxing operations will occur which can hurt performance of your application.
精彩评论