3 回答

TA貢獻1856條經驗 獲得超5個贊
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
通常,要支持any IList<T>,您需要檢查接口:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}

TA貢獻1864條經驗 獲得超2個贊
給定一個對象,我懷疑是某種的IList<>,我怎么能確定的東西它是一個IList<>?
這是勇敢的解決方案。它假定您具有要測試的實際對象(而不是Type)。
public static Type ListOfWhat(Object list)
{
return ListOfWhat2((dynamic)list);
}
private static Type ListOfWhat2<T>(IList<T> list)
{
return typeof(T);
}
用法示例:
object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();
版畫
typeof(DateTime)

TA貢獻1963條經驗 獲得超6個贊
Marc的答案是我為此使用的方法,但是為了簡單起見(以及更友好的API?),您可以在集合基類中定義一個屬性,如果您具有以下屬性:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
我發現這種方法很有用,并且對于任何泛型新手來說都很容易理解。
- 3 回答
- 0 關注
- 3691 瀏覽
添加回答
舉報