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