通过创建通用方式的C#类的intance [英] Create intance of any C# class by generic way

查看:189
本文介绍了通过创建通用方式的C#类的intance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过通用的方法来创建的类的实例。
是可能的吗?我知道,这是疯狂的,但是这仅仅是一个问题等待了它的答案。



我试过,但不起作用。

 公共类布拉布拉{
公共无效喇嘛();
}

公共类Foo< T>
{

&字典LT;字符串函数功能:LT;对象>>厂;

公共美孚()
{
厂=新词典<字符串函数功能:LT;对象>>();
}

公共WrapMe(字符串键)
{

factory.Add(键,()=>新建T());

}
}

&符LT;布拉布拉>富=新的Foo<&布拉布拉GT;();
foo.Wrapme(myBlabla);
无功实例= foo.factory [myBlabla];
instance.Bla();


解决方案

您只需要一个方法:

 静态牛逼InstantiateInstance< T>()其中T:新的()
{
返回新T();
}


i want to create instance of any class by generic way. is that possible?i know ,this is madly but this is only a question waits the its answer.

i tried this but doesnt work.

public class blabla {
 public void bla();
}

public class Foo<T>
{

        Dictionary<string, Func<object>> factory;

        public Foo()
        {
          factory = new Dictionary<string, Func<object>>();
        }

        public WrapMe(string key)
        {

            factory.Add(key, () => new T());

        }
 }

 Foo<blabla> foo = new Foo<blabla>();
 foo.Wrapme("myBlabla");
 var instance = foo.factory["myBlabla"];
 instance.Bla();

解决方案

You only need a method:

static T InstantiateInstance<T>() where T : new()
{
    return new T();
}

这篇关于通过创建通用方式的C#类的intance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆