gpt4 book ai didi

c# - 多态,调用正确的函数

转载 作者:行者123 更新时间:2023-12-04 06:17:52 24 4
gpt4 key购买 nike

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

请让我知道需要我提供哪些其他信息才能获得正确答案,因为我不确定这是否足够或过于模糊。让我特别知道我需要提供什么,因为我也是 C# 新手。

最佳答案

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

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

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();

关于c# - 多态,调用正确的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com