Jim*_*mer 2 .net c# polymorphism
鉴于:
interface I
{
}
class B: I
{
}
class C: I
{
}
class A
{
public void Method(B arg)
{
}
public void Method(C arg)
{
}
public void Method(I arg)
{
// THIS is the method I want to simplify.
if (I is B)
{
this.Method(arg as B);
}
else if (I is C)
{
this.Method(arg as C);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道有更好的方法来设计这种类型的交互,但由于细节需要很长时间来解释这是不可能的.由于这种模式会重复多次,我想用一般的实现来替换条件逻辑,我只能使用一行.我看不到实现这个泛型方法/类的简单方法,但我的直觉告诉我它应该是可能的.
任何帮助,将不胜感激.
jop*_*jop 16
我将该方法放在接口中,然后让多态决定调用哪个方法
interface I
{
void Method();
}
class B : I
{
public void Method() { /* previously A.Method(B) */}
}
class C : I
{
public void Method() { /* previously A.Method(C) */ }
}
class A
{
public void Method(I obj)
{
obj.Method();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您需要添加新类时,您只需要实现I.Method.你不需要触摸A.Method.
| 归档时间: |
|
| 查看次数: |
1176 次 |
| 最近记录: |