我有以下情况:
public class Restriction
{
public string RestrictionName { get; set; }
public bool Eval(decimal Value2)
{
Type typeRestriction = Type.GetType(RestrictionName);
return (bool)typeRestriction.InvokeMember("Eval",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
null,
new object[] { this, Value2 });
}
/* Nested Classes */
class A
{
public static bool Eval(Restriccion r, decimal value)
{
// Do something
}
}
class B
{
public static bool Eval(Restriccion r, decimal value)
{
// Do something
}
}
}
当我尝试:
Restriction r = new Restriction();
r.RestrictionName = "A";
r.Value = 15;
r.Eval(16);
我得System.NullReferenceException: Object reference not set to an instance of an object.
Debug告诉我typeRestriction
为空。为什么?嵌套类是否有特殊处理?
答案 0 :(得分:2)
在此方案中,类型A
和B
是嵌套类型。因此,他们的名字分别是Restriction+A
和Restriction+B
。此外,名称中必须包含包含Restriction
的命名空间。例如,如果名称空间为ConsoleApplication
,则需要使用名称ConsoleApplication.Restriction+A
作为A
的名称。
答案 1 :(得分:0)
这是一个命名空间问题,请尝试使用以下命令引用类类型:
Type typeRestriction = Type.GetType(string.Format("Restriction+{0}", RestrictionName));