0

我有一个问题,我想做一个通用方法来实例化模型车的表,显然是通过字符串。

我应用了这段代码:

object item = Activator.CreateInstance(Type.GetType("eStartService." + tableName));

当 I 时item.*something*,我看不到应该调用的表的属性。

这是我第一次使用反射,也许我做错了什么?

4

1 回答 1

0

这是因为编译器和智能感知将实例化的对象视为“对象”而不是实际类型。对象类型不具有您期望的属性。您需要将实例化的对象转换为相关类型。像这样的东西:

YourType item = (YourType)Activator.CreateInstance(Type.GetType("YourType"));
item.property = ...;

但是由于您的类型是在运行时而不是编译时确定的,因此您必须使用其他方法:

定义类型之间的公共接口

如果要实例化的所有类型都有共同的行为,您可以定义一个共同的接口,并在这些类型中实现它。然后您可以将实例化类型转换为该接口并使用它的属性和方法。

interface IItem { 
   int Property {
       get;
      set;
   }
}
class Item1 : IItem {
    public int Property {
        get;
       set;
    }
}
class Item2 : IItem {
    public int Property {
        get;
       set;
    }
}
IItem item = (IItem)Activator.CreateInstance(Type.GetType("eStartService." + tableName));
item.Property1 = ...;

使用反射

您可以使用反射来访问实例化类型的成员:

Type type = Type.GetType("eStartService." + tableName);
object item = Activator.CreateInstance(type);
PropertyInfo pi = type.GetProperty("Property", BindingFlags.Instance);
pi.SetValue(item, "Value here");

当然,在这种情况下没有智能感知。

使用动态类型

dynamic item = Activator.CreateInstance(Type.GetType("eStartService." + tableName));
item.Property = ...;

上面的代码可以编译,但您仍然看不到智能感知建议,因为“表”类型是在运行时确定的。

于 2015-05-20T09:16:45.733 回答