检测通用类型是否打开? [英] Detect if a generic type is open?
本文介绍了检测通用类型是否打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序集中有很多常规,关闭和打开的类型.我有一个查询,试图从中排除开放类型
I have a bunch of regular, closed and opened types in my assembly. I have a query that I'm trying to rule out the open types from it
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
为null(以及其他类似DeclaringMethod
的东西)-因此,这可能是一种方法:
Upon debugging the generic arguments of an open type, I found that their FullName
is null (as well as other things like the DeclaringMethod
) - So this could be one way:
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
是否有内置的方式可以知道类型是否打开?如果没有,还有更好的方法吗?谢谢.
Is there a built-in way to know if a type is open? if not, is there a better way to do it? Thanks.
推荐答案
You could use IsGenericTypeDefinition
:
typeof(Bar<,>).IsGenericTypeDefinition // true
typeof(Bar<int, string>).IsGenericTypeDefinition // false
这篇关于检测通用类型是否打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文