2

我有以下情况:

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

4

2 回答 2

2

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

于 2013-03-15T15:04:11.720 回答
0

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

Type typeRestriction = Type.GetType(string.Format("Restriction+{0}", RestrictionName));
于 2013-03-15T14:54:39.257 回答