在 C# 3.5 中获取类型参数约束类的类型
本文关键字:参数约束 类型 取类型 获取 | 更新日期: 2023-09-27 17:57:15
我正在尝试获取我无权编辑的自定义类的类型,并且它的声明具有参数类型约束。就像这样:
public class GenericItemCollection<T> where T : System.IEquatable<T>
{
public GenericItemCollection();
public GenericItemCollection(string json);
public int Count { get; }
public List<T> Created { get; }
public List<T> Current { get; }
public List<T> Deleted { get; }
public List<T> Original { get; }
public List<T> Updated { get; }
public void AcceptChanges();
public void AddItem(T item);
public void BindItem(T item);
public void DeleteItem(T item);
public void UpdateItem(T item);
}
}
所以我想要的是 GenericItemCollection 类型,而 T 实际上是某种东西。即:
private void MyMethod<T>(GenericItemCollection<T> genericList){
Type listType = typeof(GenericItemCollection<typeof(T)>);
//...
}
将这样称呼:
MyMethod<Foo>(fooGenericList);
MyMethod<Bar>(barGenericList);
在这种情况下,我希望列表类型
GenericItemCollection<Foo>
和
GenericItemCollection<Bar>
我知道typeof(T)在运行时之前不存在,但它应该返回一个类型,但VS只是说"预期类型"
GenericItemCollection<typeof(T)>
我不是很熟练地使用泛型,所以我显然错过了一些东西,我希望你们指出那是什么。非常感谢。
首先,应用于泛型类型参数的任何约束GenericItemCollection
也必须应用于泛型类型参数MyMethod
private void MyMethod<T>(GenericItemCollection<T> genericList) where T: IEquatable<T>
然后,只需将typeof(T)
替换为T
Type listType = typeof(GenericItemCollection<T>);