隐藏通用派生类中的基类方法 [英] Hide a base class method in a generic derived class
问题描述
我有这样一个基类:
class FooBase
{
public bool Do(int p) { /* Return stuff. */ }
}
这样的子类:
class Foo<T> : FooBase
{
private Dictionary<T, int> Dictionary;
public bool Do(T p)
{
int param;
if (!Dictionary.TryGetValue(p, out param))
return false;
return base.Do(param);
}
}
如果用户创建 Foo< string>
对象名为fooString,然后他可以同时调用 fooString.Do(5)
和 fooString。做(测试)
但如果他创建一个名为fooInt的 Foo< int>
对象,他只能调用该方法的Do方法派生类。无论 T
是什么,我更喜欢第二种。
If the user creates a Foo<string>
object called "fooString", then he can call both fooString.Do(5)
and fooString.Do("test")
but if he creates a Foo<int>
object called "fooInt", he can only call the Do method of the derived class. I prefer the second no matter what the T
is.
这两个类中的Do方法基本上都是一样。派生类中的一个使用给定参数从 Dictionary< T,int>
获取一个整数,并使用它调用基类的Do方法。
The Do methods in both of these classes essentially do the same thing. The one in the derived class gets an integer from a Dictionary<T, int>
using the given parameter and calls the Do method of the base class using it.
这就是为什么我想在 Foo< T> $中隐藏
FooBase
的Do方法C $ C>。我怎样才能实现这个或类似的东西?任何克服这一点的设计建议都会很好。
That's why I want to hide the Do method of the FooBase
in Foo<T>
. How can I achieve this or something similar? Any design advice to overcome this would also be nice.
推荐答案
但是如果他创建一个
Foo< int>
对象名为fooInt,他只能调用派生类的Do方法。
but if he creates a
Foo<int>
object called "fooInt", he can only call the Do method of the derived class.
不,这不是真的。如果声明的变量类型是 FooBase
,它仍然会调用 FooBase
方法。你并没有真正阻止访问 FooBase.Do
- 你只是隐藏它。
No, that's not true. If the declared type of the variable is FooBase
, it will still call the FooBase
method. You're not really preventing access to FooBase.Do
- you're just hiding it.
FooBase foo = new Foo<int>();
foo.Do(5); // This will still call FooBase.Do
完整示例代码显示:
using System;
class FooBase
{
public bool Do(int p) { return false; }
}
class Foo<T> : FooBase
{
public bool Do(T p) { return true; }
}
class Test
{
static void Main()
{
FooBase foo1 = new Foo<int>();
Console.WriteLine(foo1.Do(10)); // False
Foo<int> foo2 = new Foo<int>();
Console.WriteLine(foo2.Do(10)); // True
}
}
这是为什么我要在Foo中隐藏FooBase的Do方法。
That's why I want to hide the Do method of the FooBase in Foo.
你需要考虑 Liskov的可替代性原则。
Foo< T>
不应来自 FooBase
(使用合成而不是继承)或 FooBase.Do
不应该是可见的(例如,使其受到保护)。
Either Foo<T>
shouldn't derive from FooBase
(use composition instead of inheritance) or FooBase.Do
shouldn't be visible (e.g. make it protected).
这篇关于隐藏通用派生类中的基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!