![](/img/trans.png)
[英]How can I enumerate through an object of type `T` when it is a IEnumerable
[英]How do I find out whether an object's type is a subclass of IEnumerable<T> for any value type T?
我需要驗證一個對象,看它是否為null,值類型或IEnumerable<T>
,其中T
是值類型。 到目前為止,我有:
if ((obj == null) ||
(obj .GetType().IsValueType))
{
valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
// TODO: check whether the generic parameter is a value type.
}
所以我發現對象為null,值類型或某些T
IEnumerable<T>
; 如何檢查T
是否為值類型?
(編輯 - 添加值類型位)
你需要檢查它實現的所有接口(注意它理論上可以為多個T
實現IEnumerable<T>
):
foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type itemType = interfaceType.GetGenericArguments()[0];
if(!itemType.IsValueType) continue;
Console.WriteLine("IEnumerable-of-" + itemType.FullName);
}
}
我的通用貢獻,檢查給定類型(或其基類)是否實現了類型為T的接口:
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
while (type != null && type != typeof(object))
{
if (type.GetInterfaces().Any(@interface =>
@interface.IsGenericType
&& @interface.GetGenericTypeDefinition() == interfaceType))
{
return true;
}
type = type.BaseType;
}
return false;
}
你能用GetGenericArguments
做些什么嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.