c# - 在泛型派生类中隐藏基类方法

标签 c# inheritance method-hiding

我有一个这样的基类:

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.Do("test")但如果他创建一个 Foo<int>一个名为“fooInt”的对象,他只能调用派生类的Do方法。不管 T 是什么,我都喜欢第二个是。

这两个类中的 Do 方法基本上做同样的事情。派生类中的一个从 Dictionary<T, int> 中获取一个整数使用给定的参数并使用它调用基类的 Do 方法。

这就是为什么我想隐藏 FooBase 的 Do 方法的原因在Foo<T> .我怎样才能做到这一点或类似的东西?任何克服这个问题的设计建议也很好。

最佳答案

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 - 你只是把它藏起来了。

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
    }
}

That's why I want to hide the Do method of the FooBase in Foo.

你需要考虑Liskov's Substitutability Principle .

要么 Foo<T>不应派生自 FooBase (使用组合而不是继承) FooBase.Do不应该是可见的(例如,使其受到保护)。

关于c# - 在泛型派生类中隐藏基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758411/

相关文章:

inheritance - 有没有办法使用 MySQL Workbench 对表继承进行建模?

css - 选择框的 css 属性不是从其父级继承的。

java - 这是方法隐藏的情况吗?

c++ - 使用 "using"声明隐藏基类方法对赋值运算符不起作用

c# - 级联下拉列表不适用于 Jquery

c# - 如何指定打开excel文件的字符串路径?

c# - 使用标签单击事件打开和关闭 tabControl

javascript - 为什么继承对象不能在继承调用中覆盖原型(prototype)函数?

java - 调用基本重绘方法?

时间:2019-05-17 标签:c#asp.netidentityandcustomroles