我有一个通用方法,我们可以在其中传递 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/