How can I create a shared variable without using generics?

I have a general 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 an interface because in C # we cannot use generic classes for type parameters. (Right?) What I want to know is, how can I make "data" a member of an interface? And at runtime, how can I determine the data type? (Data can be any ValueType)

+3
source share
2 answers

You can only make a datamember of the interface, making it weakly typed as object:

public interface IComputeVariable
{
    object Data { get; }
}

(Note that this must be a property - you cannot specify fields in interfaces.)

, , ComputeScalar<T>, , .

SomeClass :

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

, , , .

+4
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; }
}
+1

Source: https://habr.com/ru/post/1757961/


All Articles