我的程序集中有一堆常规的、封闭的和开放的类型。我有一个查询,我试图从中排除开放类型
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
是否有内置方法可以知道类型是否开放?如果没有,有更好的方法吗?谢谢。
你可以使用IsGenericTypeDefinition http://msdn.microsoft.com/en-us/library/system.type.isgenerictypedefinition(v=vs.110).aspx:
typeof(Bar<,>).IsGenericTypeDefinition // true
typeof(Bar<int, string>).IsGenericTypeDefinition // false
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)