如何在c#中编写一个泛型函数,根据类的类型调用不同的函数?
我有以下一般课程:如何在c#中编写一个泛型函数,根据类的类型调用不同的函数?,c#,generics,generic-function,C#,Generics,Generic Function,我有以下一般课程: public class SearchModel<T> { public string Name { get; set; } public int? UserId { get; set; } public List<T> result { get; set; } } public class A{ .. .. } public class B{ .. .. } 公共类搜索模型 { 公共字符
public class SearchModel<T>
{
public string Name { get; set; }
public int? UserId { get; set; }
public List<T> result { get; set; }
}
public class A{
..
..
}
public class B{
..
..
}
公共类搜索模型
{
公共字符串名称{get;set;}
public int?UserId{get;set;}
公共列表结果{get;set;}
}
公共A类{
..
..
}
公共B级{
..
..
}
SearchModel类中的列表可以是A/B类型。
现在我有了这两个函数调用,它们给出了适当的结果
public List<A> SearchApplicationsForA(SearchModel<A> model){
}
public List<B> SearchApplicationsForB(SearchModel<B> model){
}
公共列表搜索应用程序FORA(搜索模型){
}
公共列表搜索应用程序FORB(搜索模型){
}
我想知道我是否可以编写一个通用函数来识别T的类型并调用相应的函数。例如
public List<T> SearchApplications<T>(SearchModel<T> model)
{
if (typeof(T) == typeof(A))
{
return SearchVerificationsForA(model);
}
else if (typeof(T) == typeof(B))
{
return SearchApplicationsForB(model);
}
}
公共列表搜索应用程序(SearchModel)
{
如果(类型(T)=类型(A))
{
返回搜索验证FORA(模型);
}
否则如果(类型(T)=类型(B))
{
返回SearchApplicationsForB(模型);
}
}
可以编写这样的函数吗 你不能吗
public List<A> SearchApplications(SearchModel<A> model) {
return SearchVerificationsForA(model);
}
public List<B> SearchApplications(SearchModel<B> model) {
return SearchVerificationsForB(model);
}
公共列表搜索应用程序(SearchModel){
返回搜索验证FORA(模型);
}
公共列表搜索应用程序(SearchModel){
返回SearchVerificationsForB(模型);
}
甚至不用费心测试类型?
你应该考虑这个语法:public List<T> SearchApplications<T>(SearchModel<T> model)
{
if (model is A)
{
return SearchVerificationsForA(model);
}
else if (model is B)
{
return SearchApplicationsForB(model);
}
}
公共列表搜索应用程序(SearchModel)
{
如果(型号为A)
{
返回搜索验证FORA(模型);
}
否则,如果(型号为B)
{
返回SearchApplicationsForB(模型);
}
}
看看这个,当你的代码不是泛型的时候,你不需要泛型方法。在这里,接口不是你最好的朋友吗?为特定类型创建一个重载。并非所有方法都需要泛型这毫无疑问是可行的,除非它使用的是函数重载,而不是泛型对象。这很可能是OP应该走的方向;但并没有真正回答所述的问题。是的,我同意,这是一个更可能的选择。我已经有两个单独的函数调用上述方法,但正在检查是否有更好的方法来编码。@coder\u kp但请注意,我的两个函数的名称相同?编辑错误的链接我尝试了这种方法,但由于参数无效,这两个函数调用无法编译。这可能是因为预期参数是这两者的模板参数。