创建Type的实例,作为方法的参数提供

时间:2009-11-17 19:19:02

标签: c# generics reflection

要实例化的类:

public class InstantiateMe
{
    public String foo
    {
        get;
        set;
    }
}

一些伪代码:

public void CreateInstanceOf(Type t)
{
    var instance = new t();

    instance.foo = "bar";
}

到目前为止,我认为我需要使用反射来完成这项工作,考虑到我想要实现的动态特性。

这是我的成功标准:

  • 创建任何类型的实例
  • 创建类型实例,而无需调用其构造函数
  • 访问所有公共属性

我非常感谢一些有用的示例代码。我不是C#的新手,但我以前从未使用过反射。

3 个答案:

答案 0 :(得分:4)

尝试以下方法来实际创建实例。

Object t = Activator.CreateInstance(t);

但是,如果没有泛型和约束,则无法静态访问成员,如示例所示。

您可以使用以下内容执行此操作

public void CreateInstanceOf<T>() where T : InstantiateMe, new()
{
    T i = new T();
    i.foo = "bar";
}

答案 1 :(得分:4)

你基本上需要使用Reflection。使用Activator.CreateInstance()构建您的类型,然后在类型上调用InvokeMember(),以设置属性:

public void CreateInstanceOfType(Type t)
{
    var instance = Activator.CreateInstance(t); // create instance

    // set property on the instance
    t.InvokeMember(
        "foo", // property name
        BindingFlags.SetProperty,
        null,
        obj,
        new Object[] { "bar" } // property value
    );
}

要访问泛型类型的所有属性并设置/获取它们,您可以使用GetProperties()返回PropertyInfo集合,您可以迭代它:

foreach (PropertyInfo property in type.GetProperties())
{ 
    property.GetValue() // get property
    property.SetValue() // set property
}   

另外,有关使用InvokeMember()的更多方法,请参阅the documentation

答案 2 :(得分:0)

由于您具有要实例化的类型,因此可以使用通用的辅助方法:

public static T New() where T : new()
{
    return new T();
}

否则,如果您要删除其他地方的类型(如动态加载的程序集)并且您无法直接访问该类型(它是某种元编程或反射数据),则应使用反射。

相关问题