Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Activator无法创建对象实例,引发MissingMethodException_C#_System.reflection_Activator - Fatal编程技术网

C# Activator无法创建对象实例,引发MissingMethodException

C# Activator无法创建对象实例,引发MissingMethodException,c#,system.reflection,activator,C#,System.reflection,Activator,一些代码: BinaryReader reader; //... JournalEntry.Instantiate((JournalEntry.JournalEntryType)reader.ReadByte(), reader) 新闻报道: public enum JournalEntryType { Invalid, Tip, Death, Level, Friend } private readonly static Dictionary&l

一些代码:

BinaryReader reader;

//...

JournalEntry.Instantiate((JournalEntry.JournalEntryType)reader.ReadByte(), reader)
新闻报道:

public enum JournalEntryType {
    Invalid,
    Tip,
    Death,
    Level,
    Friend
}

private readonly static Dictionary<JournalEntryType, Type> instantiationBindings = new Dictionary<JournalEntryType, Type>() {
    {JournalEntryType.Invalid, typeof(JournalEntryOther)},
    {JournalEntryType.Tip, typeof(JournalEntryTip)},
    {JournalEntryType.Death, typeof(JournalEntryOther)},
    {JournalEntryType.Level, typeof(JournalEntryOther)},
    {JournalEntryType.Friend, typeof(JournalEntryOther)}
};

internal JournalEntry(BinaryReader reader) {
    Read(reader);
}

internal static JournalEntry Instantiate(JournalEntryType type, BinaryReader reader) {
    return (JournalEntry)Activator.CreateInstance(instantiationBindings[type], reader);;
}
最顶端的代码由一个值为1的字节调用,该字节映射到
JournalEntryType.Tip

当我尝试运行此代码时,它抛出
System.MissingMethodException:“找不到类型为“JournalEntryIP”的构造函数。”


为什么呢?构造函数存在,应该使用正确的参数调用。

因为构造函数是内部的,所以需要跳过一些限制来调用它。因此,如果可以,可以将其公开,或者另一种方法是调用构造函数,如下所示:

// First get the relevant constructor
var constructor = instantiationBindings[type]
    .GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance, //Allow for internal ctors
        null,
        new[] { typeof(BinaryReader) }, // And the ctor takes a BinaryReader
        null);

// Invoke the constructor
return (JournalEntry)constructor.Invoke(new[] { reader});

构造函数必须是公共的,才能工作。
// First get the relevant constructor
var constructor = instantiationBindings[type]
    .GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance, //Allow for internal ctors
        null,
        new[] { typeof(BinaryReader) }, // And the ctor takes a BinaryReader
        null);

// Invoke the constructor
return (JournalEntry)constructor.Invoke(new[] { reader});