maf*_*afu 97 .net c# reflection constructor types
我想检查运行时已知的类型是否提供无参数构造函数.这Type堂课并没有带来任何好处,所以我假设我必须使用反思?
Ale*_*x J 164
这Type堂课是反思.你可以做:
Type theType = myobject.GetType(); // if you have an instance
// or
Type theType = typeof(MyObject); // if you know the type
var constructor = theType.GetConstructor(Type.EmptyTypes);
Run Code Online (Sandbox Code Playgroud)
如果无参数构造函数不存在,它将返回null.
如果您还想查找私有构造函数,请使用稍长的:
var constructor = theType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
Run Code Online (Sandbox Code Playgroud)
值类型有一个警告,不允许使用默认构造函数.您可以使用该Type.IsValueType属性检查是否具有值类型,并使用创建实例Activator.CreateInstance(Type);
naw*_*fal 13
type.GetConstructor(Type.EmptyTypes) != null
Run Code Online (Sandbox Code Playgroud)
会失败struct的.更好地扩展它:
public static bool HasDefaultConstructor(this Type t)
{
return t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null;
}
Run Code Online (Sandbox Code Playgroud)
成功甚至enums都有默认的无参数构造函数.由于未进行反射调用,因此值类型也略微加快.
Hen*_*man 12
是的,你必须使用Reflection.但是你在使用时已经这样做了GetType()
就像是:
var t = x.GetType();
var c = t.GetConstructor(new Type[0]);
if (c != null) ...
Run Code Online (Sandbox Code Playgroud)
这应该工作:
myClass.GetType().GetConstructors()
.All(c=>c.GetParameters().Length == 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25152 次 |
| 最近记录: |