开发者

Using C# Type as generic

I'm trying to create a generic list from a specific Type that is retrieved from elsewhere:

Type listType; // Passed in to function, could be anything
var list = _service.GetAll<listType>();

However I get a build error of:

The type or namespace name 'listType' could not be found (are you missing a using directive or an assembly reference?)

Is this even possible or am I setting foot onto C# 4 Dynamic territory?

As a background: I want to automatically load all lists with data from the repository. The code below get's passed a Form Model whose properties are iterated for any IEnum (where T inherits from DomainEntity). I want to fill the list with objects of the Type the list made of from the repository.

public void LoadLists(object model)
{
    foreach (var property in model.GetType()
        .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
   {
        if (开发者_StackOverflow中文版IsEnumerableOfNssEntities(property.PropertyType))
        {
            var listType = property.PropertyType.GetGenericArguments()[0];

            var list = _repository.Query<listType>().ToList();

            property.SetValue(model, list, null);
        }
    }
}


You can't pass a variable as a generic type/method parameter, however you can do some simple things using reflection, for example you can construct list this way:

Type listType = typeof(int);
var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(listType));

Not sure if it will be helpful, since you'll need to cast that list to something to make it useful, and you cant simply cast it to a generic type/interface without specifying generic type parameters.

You can still add/enumerate such list by casting it to non-generic versions of interfaces ICollection, IList, IEnumerable.


You need to tell it the type that listType is

var list = _repository.Query<typeof(listType)>().ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜