我正在通过Asp.Net MVC课程并了解到,对于一种方法来确定控制器的动作,
我对某些泛型有所了解并在某种程度上使用它们,但是:
该System.Type类型包含属性IsGenericTypeDefinition和ContainsGenericParameters.阅读完MSDN文档后,我得出结论,两个属性都存在,以检查类型是开放类型还是封闭类型.
但是,我没有看到两者之间的区别,以及何时想要使用另一个.
Type.IsGenericType和之间有什么区别Type.IsGenericTypeDefinition?有趣的是,MSDN的IsGenericTypeDefinition链接已被破坏.
在尝试检索给定DbContext中定义的所有DbSets后,我发现了以下内容,我试图理解这种行为:通过IsGenericType过滤属性返回所需的结果,而不使用IsGenericTypeDefinition(不返回任何).
有趣的是,从这篇文章中我得到的印象是作者使用IsGenericTypeDefinition获得了他的DbSets,而我却没有.
按照说明讨论的示例:
private static void Main(string[] args)
{
A a = new A();
int propertyCount = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType).Count();
int propertyCount2 = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericTypeDefinition).Count();
Console.WriteLine("count1: {0} count2: {1}", propertyCount, propertyCount2);
}
// Output: count1: 1 count2: 0
public class A
{
public string aaa { get; set; }
public List<int> myList { get; set; }
}
Run Code Online (Sandbox Code Playgroud) 我的程序集中有一堆常规,封闭和打开的类型.我有一个查询,我试图排除它的开放类型
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"
Run Code Online (Sandbox Code Playgroud)
在调试open类型的泛型参数时,我发现它们FullName是null(以及其他类似的东西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
Run Code Online (Sandbox Code Playgroud)
有没有内置的方法来知道类型是否打开?如果没有,有没有更好的方法呢?谢谢.