i would like to construct a generic class with generic parameters without knowing the type.
List<T> genericList = new List<T>();
public void AddGenericValue<T>(T t1, T t2)
{
for (int i = 0; i < genericList.Count; i++)
{
if (genericList[i].t1 == t1)
{
genericList[i].t2 = t2;
return;
}
}
genericList.Add(new GenericClass(t1, t2));
}
public class GenericClass<T>
{
T t1;
T t2;
public GenericClass(T t1, T t2)
{
this.t1 = t1;
this.t2 = t2;
}
}
Now i get error Using the generic type 'GenericClass' requires 1 type of argument.
You need to specify the generic parameters when stating the type:
new GenericClass<T>(t1, t2)
The reason for this is that type parameters cannot be inferred for classes, only for methods. You can make use of this by writing a factory:
static class GenericClassFactory
{
public static GenericClass<T> Create(T t1, T t2)
{
return new GenericClass<T>(t1, t2);
}
}
Now you can:
var foo = GenericClassFactory.Create(1, 2);
And T
will be deduced by the compiler.
Also, the list should be a the right type:
var genericList = new List<GenericClass<T>>();
If you need to store the list as a member variable then you'll need to promote the generic type to the class level rather than the method level:
class Foo<T>
{
private readonly List<GenericClass<T>> genericList = new List<GenericClass<T>>();
public void AddGenericValue(T t1, T t2)
{
for (int i = 0; i < genericList.Count; i++)
{
if (genericList[i].t1 == t1)
{
genericList[i].t2 = t2;
return;
}
}
genericList.Add(new GenericClass<T>(t1, t2));
}
}
This may fix your issue:
List<GenericClass<T>> genericList = new List<GenericClass<T>>();
genericList.Add(new GenericClass<T>(t1, t2));
Two things you need here,
Your instance of class should expect generic parameter ie <T>
, so create instance of GenericClass
like
new GenericClass<T>(t1, t2)
To avoid compile time error define your List properly
List<GenericClass<T>> genericList = new List<GenericClass<T>>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.