【发布时间】:2019-01-15 21:31:08
【问题描述】:
我正在尝试从我的代码中删除多余的 if-else 逻辑,但仍然 根据用户的选择执行适当的方法。
我在 main 方法中遇到编译器错误..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp5
{
public interface IBaseService<TVM> where TVM : IBaseVM
{
TVM Method1();
void Method2(TVM param);
}
public interface IBaseVM
{
int Id { get; set; }
string Name { get; set; }
}
public class Child1VM : IBaseVM
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Child2VM : IBaseVM
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Child1Service : IBaseService<Child1VM>
{
public Child1VM Method1() { return new Child1VM(); }
public void Method2(Child1VM param)
{
return; //body... }
}
}
public class Child2Service : IBaseService<Child2VM>
{
public Child2VM Method1() { return new Child2VM(); }
public void Method2(Child2VM param)
{
return; //body... }
}
}
public class Driver
{
public static void Main(string[] ars)
{
IBaseService<Child1VM> child1Service = new Child1Service(); // why cant this be of IBaseVM type ?
IBaseService<Child2VM> child2Service = new Child2Service(); // why cant this be of IBaseVM type ?
IBaseService<IBaseVM>[] services = new IBaseService<IBaseVM>[]
{
child1Service, // error
child2Service // error
};
}
}
}
我希望能够调用子服务而不必使用 if-else / switch case 逻辑。
如果所有子类都可以存储在上述数组中,我可以根据用户的选择简单地调用适当子类的适当方法(使用数组索引)。
【问题讨论】:
-
此代码未显示您指定的任何错误。相反,它显示了其他几个错误,例如: 1. Child1VM 道具必须是公共的。 2. Method2必须有返回类型。
-
我仍然收到一个错误,这些是与问题无关的非常明显的事情。虽然固定..
-
您遇到了哪个错误?您的代码至少会产生 6 个不同的错误,而且它们都与您的问题无关。
-
你还没有解决我在第一条评论中告诉你的问题。 Method2 必须有一个返回类型。你不能在接口中定义构造函数。
-
替换为完整的可编译代码(没有我想要修复的错误)
标签: c# generics interface polymorphism parametric-polymorphism