我知道我可以创建一个泛型方法,我可以从类似下面的其他方法调用,但是当我想要做的是在方法中定义一个变量时,有一个单独的方法似乎是浪费通用
private List<T> OrderedEntityList<T>(IRepository<T> repository) where T : Entity, IOrderedEntity
{
return repository.All().OrderBy(x => x.DisplayOrder).ToList();
}
public SomeMethod()
{
entityList = OrderedEntityList(_memberRepository);
foreach (var entityRecord in entityList)
{
//... do work ...
}
}
我想要的是做类似下面的事情,我可以将存储库的名称作为参数传递,但实际上,这不会编译。
public SomeMethod(string repositoryName)
{
List<T> entityList where T : Entity, IOrderedEntity = repository<T>.All().OrderBy(x => x.DisplayOrder).ToList();
foreach (var entityRecord in entityList)
{
//... do work ...
}
}
有关如何做到这一点的任何想法?
---编辑---
感谢大家的快速反馈。看起来我需要提供一些额外的信息。基本上我重命名了我的方法以使示例更容易,但实际上,我想要做的是在MVC控制器中有一个通用操作,可用于显示实体列表(所有实体都继承自Entity和IOrderedEntity )可能包括成员,状态,角色等。我试图使我的MVC控制器操作可重用,而不管底层存储库的类型(只要每个实现相同的接口)。这是我在控制器中的实际List方法,我试图使其成为“通用”。
public ActionResult List(string entity)
{
//TODO: Find out how to declare this as a generic list instead of tying it to MemberStatus
List<MemberStatus> entityList;
EntityIndexViewModel<OrderedEntityViewModel> indexViewModel;
//TODO: Possibly move this switch statement to an EntityFactory (once I find out how...)
switch (entity)
{
case "Status":
indexViewModel = new EntityIndexViewModel<OrderedEntityViewModel>();
//TODO: This is another line that I think is a waste to have as seperate method... but maybe I'm wrong
entityList = OrderedEntityList(_memberStatusRepository);
ViewBag.EntityName = "Member Statuses";
break;
default:
throw new Exception("Entity is not valid");
}
foreach (var entityRecord in entityList)
{
var viewModel = new OrderedEntityViewModel();
viewModel.Id = entityRecord.Id;
viewModel.Name = entityRecord.Name;
viewModel.DisplayOrder = entityRecord.DisplayOrder;
viewModel.HasChildRecordsAssigned = _memberRepository.All().Any(m => m.StatusId == entityRecord.Id);
indexViewModel.EntityList.Add(viewModel);
}
return View("List", indexViewModel);
}
答案 0 :(得分:4)
你可以这样做:
public SomeMethod<T>(string repositoryName) where T : Entity, IOrderedEntity
{
List<T> entityList = repository<T>.All().OrderBy(x => x.DisplayOrder).ToList();
foreach (var entityRecord in entityList)
{
//... do work ...
}
}
但是根据您的其余代码,您可能真正想要的是利用generic type variance in C# 4.0。
答案 1 :(得分:1)
您可以定义类中的T或方法签名:
public class MyClass<T> where T : Entity, IOrderEntity
{
public SomeMethod(string repositoryName)
{
...
}
}
OR
public SomeMethod<T>(string repositoryName) where T : Entity, IOrderEntity
{
...
}