C# Activator.CreateInstance - 如何创建具有参数化构造函数的类的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1288310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Activator.CreateInstance - How to create instances of classes that have parameterized constructors
提问by Chris
I have read a few bits and bobs online about this topic but found none that work for me. What I am trying to do is create a class of a runtime Type.
我已经在网上阅读了一些关于这个主题的文章,但没有发现对我有用。我想要做的是创建一个运行时类型的类。
I use Activator.CreateInstance
which works fine for classes with constructors that contain no arguments. For those with arguments it throws an exception, is there a way around this?
我使用Activator.CreateInstance
which 可以很好地用于构造函数不包含参数的类。对于那些有参数的人会抛出异常,有没有办法解决这个问题?
I am more than happy to pass null values or empty values to the ctor so long as I can create the class itself.
只要我可以创建类本身,我就非常乐意将空值或空值传递给 ctor。
采纳答案by Chris
I eventually ended up doing something like this - some of the commentors hinted towards this solution anyway.
我最终做了这样的事情 - 一些评论者无论如何都暗示了这个解决方案。
I basically iterated through all available constructors and chose the simplest. I then created null data to pass into the ctor (for what Im using it for this approach is fine)
我基本上遍历了所有可用的构造函数并选择了最简单的。然后我创建了空数据以传递给 ctor(对于我将它用于这种方法的内容很好)
Part of the code looks a little like this
部分代码看起来有点像这样
// 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());
}
回答by Marc Gravell
There is an overload that accepts arguments as a params object[]
:
有一个重载接受参数作为 a params object[]
:
object obj = Activator.CreateInstance(typeof(StringBuilder), "abc");
Would this do? Alternative, you can use reflection to find the correct constructor:
这行吗?或者,您可以使用反射来找到正确的构造函数:
Type[] argTypes = new Type[] {typeof(string)};
object[] argValues = new object[] {"abc"};
ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes);
object obj = ctor.Invoke(argValues);
回答by pezi_pink_squirrel
Activator.CreateInstance also has a whole bunch of overloads, one you might want to check out is ( Type type, params object[] args ). Simply supply the required constructor arguments to the second parameter of this call.
Activator.CreateInstance 也有一大堆重载,您可能想要检查的是( Type type, params object[] args )。只需向此调用的第二个参数提供所需的构造函数参数。
Make sure you handle exceptions here though, as it's easy to pass incorrect parameters in or for something to change in the type's constructors later on that breaks it..
确保你在这里处理异常,因为很容易在类型的构造函数中传递不正确的参数,或者稍后在类型的构造函数中更改某些内容,这会破坏它..
回答by Sam Harwell
I'm using this method to get around an issue I ran into, and it seems to be working exactly as I hoped. :)
我正在使用这种方法来解决我遇到的一个问题,它似乎完全按照我的希望工作。:)
object instance = Activator.CreateInstance(
typeof(OpCode),
BindingFlags.NonPublic | BindingFlags.Instance,
default(Binder),
new object[] { stringname, pop, push, operand, type, size, s1, s2, ctrl, endsjmpblk, stack },
default(CultureInfo));
回答by thames
As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code. Note that some modifications may need to be done based upon the number of ctor params. The code provided only allows 1 ctor param but can be modified to have more than 1. See comments in code.
作为 Activator.CreateInstance 的替代方案,链接 url 中的 FastObjectFactory 比 Activator 更好(从 .NET 4.0 开始,明显优于 .NET 3.5。没有使用 .NET 4.5 完成测试/统计)。有关统计信息、信息和代码,请参阅 StackOverflow 帖子。请注意,可能需要根据 ctor 参数的数量进行一些修改。提供的代码只允许 1 个 ctor 参数,但可以修改为超过 1 个。请参阅代码中的注释。
How to pass ctor args in Activator.CreateInstance or use IL?