C#将变量声明为泛型,而不是使用泛型方法

本文关键字:泛型方法 变量 声明 泛型 | 更新日期: 2023-09-27 18:20:07

我知道我可以创建一个通用方法,我可以从类似于以下的其他方法中调用它,但当我只想在方法中定义一个变量为通用时,拥有一个单独的方法似乎是一种浪费:

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

C#将变量声明为泛型,而不是使用泛型方法

您可以这样做:

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 ...
    }
}

但根据您代码的其余部分,也许您真正想要的是利用C#4.0中的泛型类型差异。

您可以定义类中的T或方法签名:

public class MyClass<T> where T : Entity, IOrderEntity
{
    public SomeMethod(string repositoryName)
    {
        ...
    }
}

public SomeMethod<T>(string repositoryName) where T : Entity, IOrderEntity
{
    ...
}