开发者

How can i make a generic variable without using generics?

I have a generic class,

class ComputeScalar<T> : IComputeVariable where T : struct
{
  开发者_开发百科 // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   T data;
}

class ComputeArray<T> : IComputeVariable where T : struct
{
   // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   T[] data;
}

and i use this class in a list in another class,

class SomeClass
{
   List<IComputeVariable> variables;
}

I created the interface because in C# we can't use generic classes for type parameters. (Right?) What i want to learn is how can i make "data" a member of interface? And during runtime how can i determine type of data? (Data can be any ValueType)


You could only make data a member of the interface by making it weakly typed as object:

public interface IComputeVariable
{
    object Data { get; }
}

(Note that it has to be a property - you can't specify fields in interfaces.)

You'd then probably want to implement that explicitly in ComputeScalar<T>, to avoid the weakly typed version from being used where the strongly typed version was available.

An alternative would be to make the interface generic, and SomeClass too:

class SomeClass<T> where T : struct
{
   List<IComputeVariable<T>> variables;
}

We don't really know enough about your situation to know which is the right approach, but those are two of your options.


interface IComputeVariable<T> where T : struct
{
  T Data { get; }
}

class ComputeScalar<T> : IComputeVariable<T> where T : struct
{
   // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   public T Data {get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜