【发布时间】:2014-11-06 19:45:29
【问题描述】:
我的程序集中有一堆常规的、封闭的和开放的类型。我有一个查询,我试图从中排除开放类型
class Foo { } // a regular type
class Bar<T, U> { } // an open type
class Moo : Bar<int, string> { } // a closed type
var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => ???);
types.Foreach(t => ConsoleWriteLine(t.Name)); // should *not* output "Bar`2"
在调试开放类型的泛型参数时,我发现它们的 FullName 为空(以及其他类似 DeclaringMethod 的东西) - 所以这可能是一种方式:
bool IsOpenType(Type type)
{
if (!type.IsGenericType)
return false;
var args = type.GetGenericArguments();
return args[0].FullName == null;
}
Console.WriteLine(IsOpenType(typeof(Bar<,>))); // true
Console.WriteLine(IsOpenType(typeof(Bar<int, string>))); // false
是否有内置方法可以知道类型是否打开?如果没有,有更好的方法吗?谢谢。
【问题讨论】:
-
您查看过
IsGenericType的文档吗?Use the ContainsGenericParameters property to determine whether a Type object represents an open constructed type or a closed constructed type. -
你需要获取所有开放类型的类型吗?...var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsGenericTypeDefinition);
-
@Dark Falcon:感谢您的意见。这也有效。我在智能感知中看到了
ContainsGenericParameterspop,但我认为如果该类型有任何通用参数,它会返回 true。阅读文档似乎不是那么回事 - 似乎“参数”与“参数”不同? @terrybozzio 不,相反,将它们过滤掉:) -
在我编辑的评论中,它会将它们过滤掉......
-
@terrybozzio 注意到了,谢谢 +1 :)
标签: c# reflection generic-type-argument