2014-08-28 50 views
-3

我想基於輸入字符串動態創建對象。並且類別映射的字符串預編爲_l將類型賦值給變量 - 'A'是一種類型,但用作'變量'?

class A {....} 
class B {....} 
var _l = new Dictionary<string, Type> { { "1", A } .... } // Error 
// 'A' is a type but is used like a 'variable' 

PropertyInfo propertyInfo = _l["0"].GetProperty("xxxx"); 
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType) 
propertyInfo.SetValue(instance, 
    Convert.ChangeType(value, propertyInfo.PropertyType), null); 

不過,我得到的

'A' 是一個類型,而是使用類似 '變量'

回答

3

您需要的錯誤typeof(A)

var _l = new Dictionary<string, Type> { { "1", typeof(A) } }; 
+0

'A'已經是一種類型。爲什麼需要'typeof'? – ca9163d9 2014-08-28 20:44:19

+1

A本身不是類型的類。你需要一個Type實例。 – 2014-08-28 20:44:56

+0

是'int','string'類型嗎?對於'A aaa = new A()',我們通常會說'aaa'的類型是'A'? – ca9163d9 2014-08-28 20:47:50

3

用途:

var _l = new Dictionary<string, Type> { { "1", typeof(A) } .... } 

改爲

相關問題