我有一个简单的代码,我希望根据某些数据设置一个类型,但我不能事先声明它,因为我不知道它将被设置为什么类型:
if(data[i].on == true){
Type1 temp = (Type1)data[i];
} else {
Type2 temp = (Type2)data[i];
}
// scope lost
temp.call();
我如何在这里维持范围?这有点令人困惑,因为我不知道在if else语句之前我必须将temp
设置为什么类型。
C#有解决方案吗?
答案 0 :(得分:1)
我会将Type1中的.call()作为虚方法,并在Type2中覆盖它,范围内的对象将来自Type1
基地:
class VirtualBase
{
public virtual void Call()
{
Console.WriteLine("This is base Call");
}
}
子:
class VirtualChild : VirtualBase
{
public override void Call()
{
Console.WriteLine("Child Call");
}
}
呼叫
VirtualTest.VirtualBase vc = new VirtualTest.VirtualChild();
vc.Call();
输出:
儿童电话
答案 1 :(得分:0)
一种可能的解决方案可能是dynamic object。
dynamic temp;
if(data[i].on == true){
temp = (Type1)data[i];
} else {
temp = (Type2)data[i];
}
temp.call(); //will work only if both the Type1 and Type2 have call method