c# - 在不知道类型的情况下构造泛型类
问题描述
我想在不知道类型的情况下构造一个具有泛型参数的泛型类。
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;
}
}
现在我得到错误使用泛型类型'GenericClass'需要一种类型的参数。
解决方案
声明类型时需要指定泛型参数:
new GenericClass<T>(t1, t2)
原因是不能为类推断类型参数,只能为方法推断。您可以通过编写工厂来使用它:
static class GenericClassFactory
{
public static GenericClass<T> Create(T t1, T t2)
{
return new GenericClass<T>(t1, t2);
}
}
现在你可以:
var foo = GenericClassFactory.Create(1, 2);
并将T
由编译器推导出来。
此外,列表应该是正确的类型:
var genericList = new List<GenericClass<T>>();
如果您需要将列表存储为成员变量,那么您需要将泛型类型提升到类级别而不是方法级别:
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));
}
}
推荐阅读
- sql - 如何将值(分隔符分隔)从具有多行的 SQL Server 表中分离为不同的列?
- android - 如何修复“java.lang.IllegalArgumentException:不是有效的地理位置:-118.2541117, 33.985805”
- ruby-on-rails - Ruby on Rails Devise 我想重定向到特定页面
- python - __init__() 得到了一个意外的关键字参数“端点”
- android - 如何在底部导航视图中添加分隔线
- java - 从java代码在android设备中安装apk
- java - 如何在java中使用反射直接在bean类的私有Setter方法中设置值
- javascript - React useState 未定义与 webpack-dev-server 一起使用
- kotlin - Dagger 2 @Provides 不能应用于 Kotlin 中的静态函数?
- java - 在 JavaFx 中实现倒数计时器时遇到问题