gpt4 book ai didi

c# - 在控制台应用程序中使用某些条件覆盖方法

转载 作者:行者123 更新时间:2023-11-30 14:26:49 25 4
gpt4 key购买 nike

我正在创建一个控制台应用程序。我有一节课,我在其中写了一些方法。现在我想在另一个类中覆盖该类的一些方法。但是只有在条件满足时才应该覆盖它。

例如,

public partial Class MainClass
{
public string GetPath()
{
string temp = Method1();
return temp;
}

protected virtual string Method1()
{
//logic
}


}

如果满足某些条件,则只调用覆盖的方法

public partial class ChildClass : MainCLass
{
public override void Method1()
{
//MY Logic
}
}

我怎样才能做到这一点?有可能吗?

最佳答案

ChildClass 中你可以这样做:

public partial class ChildClass : MainCLass
{
public override void Method1()
{
if(condition)
{
base.Method1();

return;
}

//YOUR LOGIC
}
}

示例

public class A
{
public virtual void MethodA()
{
Console.WriteLine("A:MethodA");
}
}

public class B : A
{
public bool CallBase { get; set; }

public B()
{
CallBase = false;
}

public override void MethodA()
{
if (CallBase)
{
base.MethodA();

return;;
}

Console.WriteLine("B:MethodA");
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();

a.MethodA();
b.MethodA();

b.CallBase = true;

b.MethodA();

A c = new B();

c.MethodA();

A d = new B(true);

d.MethodA();

Console.ReadKey();
}
}

输出

A:MethodA B:MethodA A:MethodA B:MethodA A:MethodA

关于c# - 在控制台应用程序中使用某些条件覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34492316/

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