【发布时间】:2015-04-29 08:25:10
【问题描述】:
假设我有一些如下所示的界面
public interface IPerson
{
Person GetPerson(string name);
Person SetPerson(Person p);
}
我的 person 对象有一些嵌套对象,可能它继承自基类。
public class Person : SomeBaseClass
{
public Name fullName {get;set;}
// some other stuff
}
现在假设以上所有内容都编译为程序集(dll)。是否可以使用反射即时实例化 Person 对象?
void Main()
{
Type type = typeof(IPerson);
var instance = Activator.CreateInstace(t);
// can't access properties of Person from instance.. :(
// I wan't to populate all the properties of the object on the fly
// but can't
}
基本上我想引用 dll 或加载程序集动态迭代所述程序集中的所有对象,创建对象并填充它们的属性,最后对这些对象及其属性做一些事情。这可能吗?似乎我只有在进行静态转换时才能访问 Person.Name。
var oops = (Person)instance; // now I can access. but I dont want to have to cast!
【问题讨论】:
-
但我不想强制转换 那么编译器如何知道实例是人还是动物?
-
SomeBaseClass是否实现了IPerson接口? -
您的
Main中的t应该是什么?不能是type,因为你不能创建接口的实例。 -
我猜你打错了。您无法实例化
IPerson,您可能打算将typeof(Person)传递给Activator.CreateInstance -
当我们在做的时候,你为什么不简单地写
var instance = (Person)Activator.CreateInstace(typeof(Person));?
标签: c# .net reflection types activator