给定以下层次结构:
class A
{
}
class B : A
{
public void Foo() { }
}
class C : A
{
public void Foo() { }
}
Run Code Online (Sandbox Code Playgroud)
这是第三方库,我无法修改它.有没有办法可以编写某种"通用模板化包装器",将Foo()方法转发给作为构造函数参数传递的适当对象?我最后编写了以下内容,它没有使用泛型,看起来相当难看:
class Wrapper
{
A a;
public Wrapper(A a)
{
this.a = a;
}
public void Foo()
{
if (a is B) { (a as B).Foo(); }
if (a is C) { (a as C).Foo(); }
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢一些模板约束Wrapper<T> where T : B or C.