[英]C# variance annotation of a type parameter, constrained to be value type
[英]Getting type of a type parameter constrained class in C# 3.5
我正在嘗試獲取自定義類的類型,該類無權進行編輯,並且其聲明具有參數類型約束。 像這樣:
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);
}
}
所以我想要的是當T實際上是某種東西時的GenericItemCollection類型。 即:
private void MyMethod<T>(GenericItemCollection<T> genericList){
Type listType = typeof(GenericItemCollection<typeof(T)>);
//...
}
可以這樣稱呼:
MyMethod<Foo>(fooGenericList);
MyMethod<Bar>(barGenericList);
在這種情況下,我希望listType為
GenericItemCollection<Foo>
和
GenericItemCollection<Bar>
我知道typeof(T)在運行時之前將不存在,但是無論如何它都應該返回一個Type,但是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>);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.