开发者

Create intance of any C# class by generic way

I want to create an instance of any class using generics. Is that possible?

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());
}

...

var foo = new Foo<blabla>();
foo.Wrapme("myBlabla");

var instance = foo.factory["开发者_如何学JAVAmyBlabla"];
instance.Bla();


There are two ways to solve this:

Variant 1: Add where T : new() to your class definition:

public class Foo<T> where T : new()
{
    ...
}

For further details, see the description of the new() constraint.


Variant 2: Pass the lambda () => new T() as a parameter to your constructor, store it in a Func<T> field and use it in WrapMe.

For further details, see this blog post


You only need a method:

private static T InstantiateInstance<T>() where T : new() => new T();


You can use Activator.CreateInstance<T>().


Use an Inversion of Control container, like Castle Windsor.


You need to use the new constraint when declaring Foo. This only works for types with a constructor with no arguments - which is fine in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜