加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 优化通用方法逻辑

发布时间:2020-12-16 01:51:41 所属栏目:百科 来源:网络整理
导读:我有一个通用方法,我们可以将T作为接口类型传递.方法返回对应T类型的数据列表.我对此方法有20-25条相同的条件如何优化逻辑. 类实现接口.示例Student类实现IStudent接口. public ObservableCollectionT GetAllT() { try { if (typeof(T) == typeof(IStudent))
我有一个通用方法,我们可以将T作为接口类型传递.方法返回对应T类型的数据列表.我对此方法有20-25条相同的条件如何优化逻辑.

类实现接口.示例Student类实现IStudent接口.

public ObservableCollection<T> GetAll<T>()
    {
        try
        {
            if (typeof(T) == typeof(IStudent))
            {                 
                return GetAll<T,Student>();
            }
            else if (typeof(T) == typeof(IZone))
            {
                return GetAll<T,Zone>();
            }
            else if (typeof(T) == typeof(IEmployee))
            {
                return GetAll<T,Employee>();
            }
            else if (typeof(T) == typeof(ICourse))
            {
                return GetAll<T,Course>();
            }
         }
    }

这里调用者传递接口类型T和I检查T的类型.我传递给其他函数T和将返回T的列表的类.其他函数在基类中我无法改变.
有谁能建议我一些相同的东西.

解决方法

你可以尝试通过反思来做到这一点.

public ObservableCollection<T> GetAll<T>()
{
    var typeName = typeof(T).FullName;
    var indexOfDot = typeName.LastIndexOf('.');
    var newTypeName = typeName.SubString(0,indexOfDot) + '.' + typeName.SubString(indexOfDot + 1);
    var newType = Type.GetType(newTypeName);
    var methodTypes = new [] { typeof(T),newType };
    var method = GetType().GetMethod("GetAll");
    var typedMethod = method.MakeGenericMethod(methodTypes);
    return (ObservableCollection<T>) typedMethod.Invoke(this,new object[0]);
}

不漂亮,但应该做的工作,并做一般.

当前方式唯一的警告是GetAll方法被泛型参数重载,因此它可能无法使您获得正确的方法,或者因为有两个方法而失败.如果可以指出正确的那个,我会看看.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读