我有以下情况:
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.
调试显示
typeRestriction
为空。为什么?嵌套类有特殊待遇吗? 最佳答案
在这种情况下,类型A
和B
是嵌套类型。因此,它们的名称分别为Restriction+A
和Restriction+B
。此外,名称中必须包含包含Restriction
的名称空间。例如,如果名称空间是ConsoleApplication
,则需要使用名称ConsoleApplication.Restriction+A
作为A
的名称。
关于c# - 嵌套类和动态调用问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15435414/