2014-08-28 97 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) } .... } 

改为

相关问题