嵌套类和动态调用问题

本文关键字:调用 问题 动态 嵌套 | 更新日期: 2023-09-27 18:04:00

我有以下场景:

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

When I Try:

    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为空。为什么?嵌套类有特殊待遇吗?

嵌套类和动态调用问题

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

这是一个命名空间问题,尝试使用:

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