C#中的继承问题 [英] Inheritence problem in C#
问题描述
作为对该论坛的测试,也是因为我不知道一个好的解决方案.
As a test for the forum and also because I don''t know a good solution.
我有一个低级基类,该基类具有受保护的方法,该方法可在隐含情况下被覆盖,例如:
I''ve got a low down base class with a protected method that is overridden on implimentations, something like:
class Foo
{
protected Bar()
{
// base work
}
}
class Tang : Foo
{
protected override Bar()
{
// my bits
base.Bar();
}
}
现在,我想拥有一个包装器类,该类可以接受任何派生的Foo(例如Tang),并完成其包装器工作,然后调用包装好的Foo.
Now I want to have a wrapper class that can take ANY derived Foo (say a Tang) and do its wrapper work then call out to the wrapped Foo.
Class Outside : Foo
{
private Foo wrapped;
Outside (Foo wrapped)
: base()
{
this.wrapped = wrapped;
}
protected override Bar()
{
// my bits
// then call the wrapped one:
this.wrapped.Bar();
}
}
现在,由于Bar受保护,而Outside与Foo在不同的命名空间中,所以我不能称其为包装. 关于什么或如何的任何想法[-700建议对Foo进行任何更改,这是不可行的]
[其他信息]
Now because Bar is protected and Outside is in a different namespace to Foo so I can''t call wrapped. Any idea of a what or how [-700 for suggesting any change to Foo, it is off limits]
[Additional Information]
我还在摆弄东西,为了使事情正常进行,我们很讨厌,但这并不理想.这是基于WrappedFoo
解决方案的.
I''m still fiddling, we did a nasty to get things working but it wasn''t ideal; this was based on the WrappedFoo
solution.
最大的问题是,Foo
的命名空间已超出范围,它在核心基础结构中,我们需要在Tang
命名空间中找到解决方案.
The big problem is that Foo
''s namespace is off-limits, it''s in the core infrastructure, and we need a solution in the Tang
namespace.
推荐答案
这不是我的强项,但也许您可以使用
wrapped
在打电话给酒吧之前?如果那不起作用,那么您可以通过以下方法使用Reflection:
This isn''t my strong point, but perhaps you could cast
wrapped
before calling Bar? If that doesn''t work, then you could use Reflection, in some method like this:
Type tp = this.wrapped.GetType();
Type baseType = tp.BaseType;
MethodInfo baseMethod = baseType.GetMethod("Bar", BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);
baseMethod.Invoke(this.wrapped, arguments);
如果DeclaredOnly不起作用,则可以尝试FlattenHierarchy.我还没有测试过,但这可能有用
If DeclaredOnly doesn''t work, then you could try FlattenHierarchy. I haven''t tested that, but it might work
我更新了您的帖子,以解决标题中的拼写错误.
I updated your post to fix a spelling error in the title by the way.
可包装的foo类如何:
How about a wrappable foo class:
class WrappableFoo : Foo
{
public void CallBar()
{
base.Bar();
}
}
然后,Tang必须继承WrappableFoo
Tang must then inherit WrappableFoo
class Tang : WrappableFoo
{
protected override Bar()
{
// my bits
base.Bar();
}
}
并且外界必须始终采用WrappableFoo
And Outside must always take a WrappableFoo
Class Outside : Foo
{
private WrappableFoo wrapped;
Outside (WrappableFoo wrapped)
: base()
{
this.wrapped = wrapped;
}
protected override Bar()
{
// my bits
// then call the wrapped one:
this.wrapped.CallBar();
}
}
这篇关于C#中的继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!