c# – 无法巧妙地将类型Void转换为类型System.Collections.Gener
发布时间:2020-12-15 20:50:06 所属栏目:百科 来源:网络整理
导读:试图返回一个泛型类型,并得到标题中描述的错误. 我相信我做的事情很傻 – 建议赞赏…… public static IListT GetGroupByIdT(int groupId) { DashboardGroupType type = (DashboardGroupType)groupId; IListT result = null; var obj = default(T); switch (
试图返回一个泛型类型,并得到标题中描述的错误.
我相信我做的事情很傻 – 建议赞赏…… public static IList<T> GetGroupById<T>(int groupId) { DashboardGroupType type = (DashboardGroupType)groupId; IList<T> result = null; var obj = default(T); switch (type) { case DashboardGroupType.Countries: break; case DashboardGroupType.Customers: // this returns a list of typ IEnumerable<Customer> obj = (T) CustomerRepository.GetAllCustomers(); break; case DashboardGroupType.Facilities: // this returns a list of typ IEnumerable<Facility> obj = (T) FacilityRepository.GetAllFacilities(); break; case DashboardGroupType.Heiarchy: break; case DashboardGroupType.Lines: break; case DashboardGroupType.Regions: // this returns a list of typ IEnumerable<string> obj = (T) CustomerRepository.GetRegionsHavingCustomers(); break; case DashboardGroupType.States: // // this returns a list of typ IEnumerable<Customer> obj = (T) CustomerRepository.GetStatesHavingCustomers(); break; case DashboardGroupType.Tanks: break; default: break; } result = result.Add(obj); // ERROR IS THROWN HERE } 解决方法
Add方法不返回任何内容.它只是更改列表.这就是你收到错误的原因.只需删除作业:
result.Add(obj); 另一个问题是你没有初始化结果.运行代码时,您将收到NullReferenceException.你需要这样的东西: IList<T> result = new List<T>(); 您还需要从此函数返回一个值.我猜你想要 return result; 根据您的意见,方法CustomerRepository.GetAllCustomers();和FacilityRepository.GetAllFacilities();并且喜欢返回IEnumerable< Customer>,或IEnumerable< Facility>或类似的实例.你将这些转换为T.这意味着所有这些类型都必须可以转换为T. 我猜你想要的是把这些集合中的所有项目都添加到列表中.如果是这种情况,你应该转换为IEnumerable< T>相反,并调用 总的来说,这似乎是一个非常糟糕的设计.根据您要实现的目标,可以使用继承和/或接口获得更好的设计. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |