C# 确定类型是否为静态类型
假设我有一个C# 确定类型是否为静态类型,c#,.net,reflection,types,instantiation,C#,.net,Reflection,Types,Instantiation,假设我有一个类型,名为类型 我想确定是否可以对我的类型执行此操作(而不是对每个类型执行此操作): 如果type是System.Windows.Point,那么我可以这样做: Point point1 = new Point(); 但是,如果type是System.Environment,则该命令将不会飞行: Environment environment1 = new Environment(); //wrong 因此,如果我迭代程序集中的每个可见类型,如何跳过所有无法创建第二个实例的类型?
类型
,名为类型
我想确定是否可以对我的类型执行此操作(而不是对每个类型执行此操作):
如果type
是System.Windows.Point
,那么我可以这样做:
Point point1 = new Point();
但是,如果type
是System.Environment
,则该命令将不会飞行:
Environment environment1 = new Environment(); //wrong
因此,如果我迭代程序集中的每个可见类型,如何跳过所有无法创建第二个实例的类型?我对反思有点陌生,所以我对术语还不是很在行。希望我在这里要做的事情非常清楚。
静态
类在IL级别声明为抽象
和密封
。因此,您可以检查isastract
属性以一次性处理抽象类和静态类(针对您的用例)
然而,abstract
类并不是唯一不能直接实例化的类型。您应该检查诸如接口()和类型之类的东西,这些东西没有可由调用代码访问的构造函数 这是一种获取程序集中所有类型的所有公共构造函数的方法
var assembly = AppDomain.CurrentDomain.GetAssemblies()[0]; // first assembly for demo purposes
var types = assembly.GetTypes();
foreach (var type in types)
{
var constructors = type.GetConstructors();
}
你可以搜索像这样的公共建筑商
Type t = typeof(Environment);
var c = t.GetConstructors(BindingFlags.Public);
if (!t.IsAbstract && c.Length > 0)
{
//You can create instance
}
或者,如果您只对无参数构造函数感兴趣,可以使用
Type t = typeof(Environment);
var c = t.GetConstructor(Type.EmptyTypes);
if (c != null && c.IsPublic && !t.IsAbstract )
{
//You can create instance
}
这将是对C#的充分检查,因为抽象类在C#中不能是密封的或静态的。但是,在处理来自其他语言的CLR类型时,需要小心
Type t = typeof(System.GC);
Console.WriteLine(t.Attributes);
TypeAttributes attribForStaticClass = TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class |
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit;
Console.WriteLine((t.Attributes == attribForStaticClass));
我想,这应该是可行的。注意,抽象类可以有一个公共
构造函数。您不必在if
语句的主体中创建类的实例。您将获得MemberAccessException
。感谢您的回答,我自己可能需要很长时间才能想出这个答案。
Type t = typeof(System.GC);
Console.WriteLine(t.Attributes);
TypeAttributes attribForStaticClass = TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class |
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit;
Console.WriteLine((t.Attributes == attribForStaticClass));