我已经在网上阅读了一些关于这个主题的内容,但发现没有一个对我有用.我要做的是创建一个运行时类型的类.
我使用Activator.CreateInstance哪个适用于具有不包含参数的构造函数的类.对于那些有参数的人会引发异常,有没有办法绕过这个?
我非常乐意将空值或空值传递给ctor,只要我可以创建类本身.
Mar*_*ell 48
有一个重载接受参数作为params object[]:
object obj = Activator.CreateInstance(typeof(StringBuilder), "abc");
Run Code Online (Sandbox Code Playgroud)
这会吗?或者,您可以使用反射来查找正确的构造函数:
Type[] argTypes = new Type[] {typeof(string)};
object[] argValues = new object[] {"abc"};
ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes);
object obj = ctor.Invoke(argValues);
Run Code Online (Sandbox Code Playgroud)
我最终最终做了类似的事情 - 一些评论员无论如何都暗示了这个解决方案.
我基本上遍历了所有可用的构造函数并选择了最简单的构造函数.然后我创建了空数据以传递到ctor(因为我使用它来处理这种方法很好)
部分代码看起来有点像这样
// If we have a ctor that requires parameters then pass null values
if (requiresParameters)
{
List<object> parameters = new List<object>();
ParameterInfo[] pInfos = constructorInfos[0].GetParameters();
foreach (ParameterInfo pi in pInfos)
{
parameters.Add(createType(pi.ParameterType));
}
return constructorInfos[0].Invoke(parameters.ToArray());
}
Run Code Online (Sandbox Code Playgroud)