简体   繁体   English

Activator.CreateInstance - 如何创建具有参数化构造函数的类的实例

[英]Activator.CreateInstance - How to create instances of classes that have parameterized constructors

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. 我使用Activator.CreateInstance ,它适用于具有不包含参数的构造函数的类。 For those with arguments it throws an exception, is there a way around this? 对于那些有参数的人会引发异常,有没有办法绕过这个?

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,只要我可以创建类本身。

There is an overload that accepts arguments as a params object[] : 有一个重载接受参数作为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);

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());
}

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));

Activator.CreateInstance also has a whole bunch of overloads, one you might want to check out is ( Type type, params object[] args ). Activator.CreateInstance也有一大堆重载,你可能想要检查的是(Type type,params object [] args)。 Simply supply the required constructor arguments to the second parameter of this call. 只需为此调用的第二个参数提供所需的构造函数参数即可。

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.. 确保你在这里处理异常,因为很容易传递不正确的参数或者稍后在类型的构造函数中更改某些东西会破坏它。

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). 作为Activator.CreateInstance的替代方案,链接url中的FastObjectFactory比Activator更好(从.NET 4.0开始,明显优于.NET 3.5。没有使用.NET 4.5进行测试/统计)。 See StackOverflow post for stats, info and code. 有关统计信息,信息和代码,请参阅StackOverflow帖子。 Note that some modifications may need to be done based upon the number of ctor params. 请注意,可能需要根据ctor参数的数量进行一些修改。 The code provided only allows 1 ctor param but can be modified to have more than 1. See comments in code. 提供的代码仅允许1 ctor param,但可以修改为超过1.请参阅代码中的注释。

How to pass ctor args in Activator.CreateInstance or use IL? 如何在Activator.CreateInstance中传递ctor args或使用IL?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM