3 c# logic class generic-method c#-4.0
我有一个通用方法,我们可以将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>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里调用者传递接口类型T和I检查T的类型.我传递给其他函数T和将返回T的列表的类.其他函数在基类中我无法改变.有谁能建议我一些相同的东西.
我认为你根本不需要通用,你可以创建一个由你所有类型实现的通用接口:
public interface IObservableElement
{
public ObservableCollection<IObservableElement> GetAll();
}
Run Code Online (Sandbox Code Playgroud)