Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建类型的实例,作为方法的参数提供_C#_Generics_Reflection - Fatal编程技术网

C# 创建类型的实例,作为方法的参数提供

C# 创建类型的实例,作为方法的参数提供,c#,generics,reflection,C#,Generics,Reflection,要实例化的类: public class InstantiateMe { public String foo { get; set; } } 一些伪代码: public void CreateInstanceOf(Type t) { var instance = new t(); instance.foo = "bar"; } 到目前为止,考虑到我想要实现的动态特性,我认为我需要使用反射来完成这项工作 以下是我的成功标

要实例化的类:

public class InstantiateMe
{
    public String foo
    {
        get;
        set;
    }
}
一些伪代码:

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

    instance.foo = "bar";
}
到目前为止,考虑到我想要实现的动态特性,我认为我需要使用反射来完成这项工作

以下是我的成功标准:

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

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

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

Object t = Activator.CreateInstance(t);
但是,如果没有泛型和约束,静态访问成员是不可能的,如示例所示

不过,你可以用下面的方法来做

public void CreateInstanceOf<T>() where T : InstantiateMe, new()
{
    T i = new T();
    i.foo = "bar";
}
public void CreateInstanceOf(),其中T:instanceme,new()
{
T i=新的T();
i、 foo=“bar”;
}

您基本上需要使用反射。使用
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()

的更多方法,请参阅,因为您拥有要实例化的类型,因此可以使用通用帮助器方法:

public static T New() where T : new() { return new T(); } 公共静态T New(),其中T:New() { 返回新的T(); }
否则,如果您正在从其他地方提取某个类型(如动态加载的程序集),并且您无法直接访问该类型(它是某种元编程或反射数据),则应使用反射。

这将是:T obj=Activator.CreateInstance();-)它应该是T ins=Activator.CreateInstance()@维姆,冈萨罗,谢谢。修复了使用非泛型CreateInstance方法的问题。很好的解决方案,尽管它似乎击败了使用泛型的目标,然后将其限制为单一类型。文档和Intellisense目前对我没有任何帮助。你能给我提供一些工作代码吗?@Wim:
Activator.CreateInstance(T)
在我尝试实例化一个无参数类时不工作。有什么想法吗?Activator.CreateInstance(typeof(T))-或者干脆T obj=new T()@Wim:您的代码似乎忽略了SetProperty绑定标志。我得到了一个System.MissingMethodExceptionOK——我最终测试了它,而不是在HTML文本框中输入