2013-03-15 84 views
3

我有以下情形:嵌套類和動態調用問題

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爲空。爲什麼?嵌套類有特殊待遇嗎?

回答

2

類型AB在這種情況下是嵌套類型。因此他們的名字分別是Restriction+ARestriction+B。此外,包含Restriction的名稱空間必須包含在名稱中。例如,如果命名空間爲ConsoleApplication,則需要使用名稱ConsoleApplication.Restriction+A作爲A的名稱。

+0

這是[記錄在這裏](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx)。 – 2013-03-15 15:21:41

0

這是一個命名空間問題,請嘗試使用引用類類型:

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

我試過'限制+ {0}'和'限制。{0}'但它沒有工作 – 2013-03-15 14:59:59

+0

它只會錯過命名空間。如果這是從另一個程序集使用的,那麼帶有版本號和東西的標準程序集名稱也必須位於字符串中。但幸運的是,這並非如此。 – 2013-03-15 15:18:19