开发者

Given a Generic <E> how to create a new E and return it?

This code returns a variable set of fields and I want to return a strongly typed <E>:

public IList<E> Get(Expression<Func<E, object>> selectLambda == null)
{
    if (selectLambda == null)
        selectLambda = p => p;
    var partialSet = D开发者_StackOverflow中文版C.CreateQuery<E>("[" + typeof(E).Name + "]");
    foreach ( var record in partialSet)
    {
        var tempEntity = new E();  // This is the error
        MapIt( record, tempContract);
        result.Add(tempContract);
    }
    return result;
}


The simplest way is to add a constraint:

public IList<E> Get(Expression<Func<E, object>> selectLambda == null)
    where E : new()

Then the rest of your code will compile :)

If you can't use constraints there (e.g. because they would propagate all over the place) but you happen to know that it will work at execution time, you could use:

var tempEntity = Activator.CreateInstance<E>();


You need a constraint for E:

public IList<E> Get() where E : new()

This way you make sure E does have a parameterless constructor.

Cheers Matthias


E must support the new () definition as per generic constraint (i.e. E must be ": new ()")


If E does not have empty constructor you can pass delegate to your method which you can use to create E. In this case caller of the method would be responsible for passing proper delegate.

public IList<E> Get(Expression<Func<E, object>> selectLambda == null, Func<E> creator)
{
    // ...
    var tempEntity = creator();  
    // ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜