Bel*_*lgi 5 c# reflection constructor system.reflection system.type
我正在尝试编写接收参数列表并获取匹配 Ctor 的 ConstructorInfo 的代码。
方法签名是ConstructorInfo GetConstructorInfo(Type type, object[] args).
我创建了一个类来使用:
public class ClassWithParamsInCtor
{
public ClassWithParamsInCtor(params int[] parameters)
{
}
}
Run Code Online (Sandbox Code Playgroud)
使用该类Activator我可以创建该对象的实例:
ClassWithParamsInCtor myclass = Activator.CreateInstance(typeof(ClassWithParamsInCtor), new object[] { 1,2 }) as ClassWithParamsInCtor; \\returns a valid instance of the class;
Run Code Online (Sandbox Code Playgroud)
但是当我尝试获取 ConstructorInfo 时出现问题,以下返回 null:
ConstructorInfo ctorInfo = typeof(ClassWithParamsInCtor).GetConstructor(new Type[] { typeof(int), typeof(int) }); \\returns null
Run Code Online (Sandbox Code Playgroud)
在这种情况下如何获取ConstructorInfo?
params int[]是一个语法糖int[],你需要使用typeof(int[])
typeof(ClassWithParamsInCtor).GetConstructor(new Type[] { typeof(int[]) });
Run Code Online (Sandbox Code Playgroud)
尝试这个,
ConstructorInfo ctorInfo = typeof(ClassWithParamsInCtor).GetConstructor(new Type[] { typeof(int[])});
Run Code Online (Sandbox Code Playgroud)
希望有帮助,