开发者

anonymous types and generics

I cannot find a way to pass an anonymous type to a generic class as a type parameter.

// this is the class I want to instantiate

public class ExtArrayStore<开发者_JAVA百科T> : IViewComponent 
{
    public IQueryable<T> Data { get; set; }

... // the creator class

public static class ArrayStoreGenerator
{
    public static ExtArrayStore<T> CreateInstance<T>(IQueryable<T> query)
    {
        return new ExtArrayStore<T>();
    }
}

// trying to use this

IQueryable usersQuery= ((from k in bo.usersselect new { userid = k.userid, k.username}).AsQueryable());
      var x = ArrayStoreGenerator.CreateInstance(usersQuery);

I am getting;

The type arguments for method ArrayStoreGenerator.CreateInstance(System.Linq.IQueryable)' cannot be inferred from the usage. Try specifying the type arguments explicitly

Is there a way to achieve this? ( I am thinking of Interfaces and returning an interface, but not sure if it would work) can any one help with passing anon types to generics.


usersQuery is being typed as the non-generic IQueryable because you explicitly specify that in the variable's declaration.

Instead, do var usersQuery = .... This will type the variable as IQueryable<TAnon>, which then matches the signature of ArrayStoreGenerator.CreateInstance.


You should define usersQuery as var.


What if you try var usersQuery local variable instead of explicitly specify its type?


Try with ToArray:

var x = ArrayStoreGenerator.CreateInstance(usersQuery.ToArray());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜