嵌套类和动态调用问题

时间:2013-03-15 14:50:40

标签: c# reflection nested-class

我有以下情况:

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为空。为什么?嵌套类是否有特殊处理?

2 个答案:

答案 0 :(得分:2)

在此方案中,类型AB是嵌套类型。因此,他们的名字分别是Restriction+ARestriction+B。此外,名称中必须包含包含Restriction的命名空间。例如,如果名称空间为ConsoleApplication,则需要使用名称ConsoleApplication.Restriction+A作为A的名称。

答案 1 :(得分:0)

这是一个命名空间问题,请尝试使用以下命令引用类类型:

Type typeRestriction = Type.GetType(string.Format("Restriction+{0}", RestrictionName));