微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 无法巧妙地将类型Void转换为类型System.Collections.Generic.IList

试图返回一个泛型类型,并得到标题中描述的错误.
我相信我做的事情很傻 – 建议赞赏……

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>相反,并调用AddRange方法.

总的来说,这似乎是一个非常糟糕的设计.根据您要实现的目标,可以使用继承和/或接口获得更好的设计.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐