多态性,称正确的功能

时间:2011-08-10 13:20:54

标签: c# asp.net polymorphism

我在多层类系统中有一个特定的函数被调用,并在调用它时选择正确的函数。如何告诉它在特定类中选择函数?

请让我知道我需要哪些其他信息才能得到正确的答案,因为我不确定这是否足够或太模糊。让我具体了解我需要提供的内容,因为我也是c#的新手。

1 个答案:

答案 0 :(得分:2)

我创建了我能想到的最基本的多态性示例。尝试理解示例和评论,如果您有更具体的问题,我会更新帖子。

第一个代码示例包含两个类,第二个代码调用这些类的对象方法来演示多态。

public class BaseClass
{
    // This method can be "replaced" by classes which inherit this class
    public virtual void OverrideableMethod()
    {
        System.Console.WriteLine("BaseClass.OverrideableMethod()");
    }

    // This method is called when the type is of your variable is "BaseClass"
    public void Method()
    {
        Console.WriteLine("BaseClass.Method()");
    }
}

public class SpecializedClass : BaseClass
{

    // your specialized code
    // the original method from BaseClasse is not accessible anymore
    public override void OverrideableMethod()
    {
        Console.WriteLine("SpecializedClass.OverrideableMethod()");

        // call the base method if you need to
        // base.OverrideableMethod();
    }

    // this method hides the Base Classes code, but it still is accessible
    // - without the "new" keyword the compiler generates a warning
    // - try to avoid method hiding
    // - it is called when the type is of your variable is "SpecializedClass"
    public new void Method()
    {
        Console.WriteLine("SpecializedClass.Method()");
    }
}

使用类似的东西测试类:

Console.WriteLine("testing base class");

BaseClass baseClass = new BaseClass();
baseClass.Method();
baseClass.OverrideableMethod();


Console.WriteLine("\n\ntesting specialized class");

SpecializedClass specializedClass = new SpecializedClass();
specializedClass.Method();
specializedClass.OverrideableMethod();


Console.WriteLine("\n\nuse specialized class as base class");

BaseClass containsSpecializedClass = specializedClass;
containsSpecializedClass.Method();
containsSpecializedClass.OverrideableMethod();