c# - 优化泛型方法逻辑

标签 c# class c#-4.0 logic generic-method

我有一个通用方法,我们可以在其中传递 T 作为接口(interface)类型。方法返回对应T类型的数据列表。对于此方法,我有 20-25 个相同的条件,我该如何优化逻辑。

类实现接口(interface)。示例 Student 类实现 IStudent 接口(interface)。

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

这里调用者传递接口(interface)类型 T,我检查 T 的类型。我传递给其他函数 T 和将返回 T 列表的类。我无法更改的基类中的其他函数。 谁能给我一些相同的建议。

最佳答案

我认为您根本不需要泛型,您可以创建一个由所有类型实现的通用接口(interface):

public interface IObservableElement
{
    public ObservableCollection<IObservableElement> GetAll();
}

关于c# - 优化泛型方法逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13703203/

相关文章:

c# - 什么以及何时使用元组?

.net - WPF DatePicker 默认为美式日期而不是英式

.net - 如何将图片从资源管理器拖放到 WPF 控件上?

c# - 保存并补充 .net Web 应用程序的状态

java - Java中类之间传递变量

c# - 信箱不可用。服务器响应为 : 5. 7.1 中继凭据无效

jquery - 如何高亮显示jsTree节点?

python - 在 Python 中,派生类可以被截断为基类吗?

c# - 跨数据注释/属性共享正则表达式的方法

c# - 使 SortableBindingList 使用稳定排序的最简单方法