激活器无法创建对象实例,引发MissingMethodException

时间:2018-12-30 02:23:05

标签: c# system.reflection activator

某些代码:

BinaryReader reader;

//...

JournalEntry.Instantiate((JournalEntry.JournalEntryType)reader.ReadByte(), reader)

JournalEntry:

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

JournalEntryTip:

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

最顶部的代码将使用一个值1的字节调用,该字节映射到JournalEntryType.Tip

当我尝试运行此代码时,它会抛出System.MissingMethodException: 'Constructor on type 'JournalEntryTip' not found.'

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

1 个答案:

答案 0 :(得分:2)

由于构造函数是内部的,因此您需要跳过几个步骤来调用它。因此,您可以将其公开,或者另一种方法是像这样调用构造函数:

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