C# 带有私有密封类的 Activator.CreateInstance

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/440016/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:28:01  来源:igfitidea点击:

Activator.CreateInstance with private sealed class

c#reflectionado.net

提问by

I'm trying to new up a LocalCommand instance which is a private class of System.Data.SqlClient.SqlCommandSet. I seem to be able to grab the type information just fine:

我正在尝试新建一个 LocalCommand 实例,它是 System.Data.SqlClient.SqlCommandSet 的私有类。我似乎能够很好地获取类型信息:

Assembly sysData = Assembly.Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
localCmdType = sysData.GetType("System.Data.SqlClient.SqlCommandSet+LocalCommand");

but Activator.CreateInstance throws an exception when I try to instantiate it:

但是当我尝试实例化它时 Activator.CreateInstance 抛出异常:

object item = Activator.CreateInstance(localCmdType,
  new object[] { commandText, parameters, num7, commandType });

System.MissingMethodException: Constructor on type 'System.Data.SqlClient.SqlCommandSet+LocalCommand' not found.

System.MissingMethodException:未找到类型“System.Data.SqlClient.SqlCommandSet+LocalCommand”的构造函数。

The constructor arguments match the signature I see in Reflector. Is new'ing up a private class with an internal ctor supported with a different CreateInstance overload or what?

构造函数参数与我在 Reflector 中看到的签名相匹配。是新建一个私有类,内部 ctor 支持不同的 CreateInstance 重载还是什么?

采纳答案by Jon Skeet

My first thought would be to get the ConstructorInfousing ConstructorInfo constructorInfo = Type.GetConstructor(), and then constructorInfo.Invoke()that. I suspect that Activator.CreateInstancemakes it hard to call constructors you wouldn't normally have access to, although I don't remember trying it myself.

我的第一个想法是获得ConstructorInfousing ConstructorInfo constructorInfo = Type.GetConstructor(),然后constructorInfo.Invoke()是。我怀疑这Activator.CreateInstance使得很难调用您通常无法访问的构造函数,尽管我不记得自己尝试过。

回答by Andrew Hare

I got it to work this way:

我让它以这种方式工作:

using System;
using System.Reflection;

class Test
{
    public String X { get; set; }

    Test(String x)
    {
        this.X = x;
    }
}

class Program
{
    static void Main()
    {
        Type type = typeof(Test);

        ConstructorInfo c = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, 
            null, new Type[] { typeof(String) }, null);

        Object o = c.Invoke(new Object[] { "foo" });
    }
}

The trick was to go after the constructor specifically with GetConstructorrather then trying to find it in the results of GetConstructors. Go figure.

诀窍是专门GetConstructor跟踪构造函数而不是尝试在GetConstructors. 去搞清楚。

回答by Andrew Hare

I might be a little late in responding, but I ran into a similar problem that fits into this topic.
I wanted to instantiate a non public constructor using Activator.CreateInstanceand passing it arguments.

我的回复可能有点晚了,但我遇到了一个适合这个主题的类似问题。
我想使用Activator.CreateInstance并传递参数来实例化一个非公共构造函数。

public class Node
{
    string name;
    Node parent;

    protected Node(string name,Node parent)
    {
       this.name = name;
       this.parent = parent;
    }

    public static Node Create(string name,Node parent)
    {
       Node result = Activator.CreateInstance(
         type: typeof(Node),
         bindingAttr: BindingFlags.Instance  | BindingFlags.NonPublic,
         binder: null, //default binder
         args: new object[] { name, parent },
         culture: null);
       return (Node)result;
    }
}

The tricky part was the binding flags.

棘手的部分是绑定标志。

My first instinct was to use BindingFlags.CreateInstance | BindingFlags.NonPublic, however that caused an exception to be thrown: MissingMethodException Constructor on type 'Node' not found.

我的第一直觉是使用BindingFlags.CreateInstance | BindingFlags.NonPublic,但这会导致抛出异常:未找到类型“节点”上的 MissingMethodException 构造函数。

回答by Dave Cousineau

Trick is to make sure to use the right CreateInstanceoverload:

诀窍是确保使用正确的CreateInstance重载:

// WRONG
... Activator.CreateInstance(
       type,
       BindingFlags.Instance
       | BindingFlags.NonPublic
    );

This calls the paramsoverload, which will default to Instance | Public | CreateInstance, and your binding flags will be passed as arguments to the constructor, giving the vague MissingMethodException.

这将调用params重载,默认为Instance | Public | CreateInstance,并且您的绑定标志将作为参数传递给构造函数,给出模糊的MissingMethodException.

Also, use Instance | Public | NonPublicif you aren't sure of the visibility of the constructor:

另外,Instance | Public | NonPublic如果您不确定构造函数的可见性,请使用:

// right
... Activator.CreateInstance(
       type,
       BindingFlags.Instance
       | BindingFlags.Public
       | BindingFlags.NonPublic,
       null,
       new object[] { }, // or your actual constructor arguments
       null
    );