gpt4 book ai didi

c# - 在哪里放置实现相同接口(interface)的多个类所需的通用逻辑?

转载 作者:行者123 更新时间:2023-11-30 13:39:15 25 4
gpt4 key购买 nike

给定以下界面:

public interface IFoo
{
bool Foo(Person a, Person b);
}

以及上述的以下两个实现:

public class KungFoo : IFoo
{
public bool Foo(Person a, Person b)
{
if (a.IsAmateur || b.IsAmateur) // common logic
return true;
return false;
}
}

public class KongFoo : IFoo
{
public bool Foo(Person a, Person b)
{
if (a.IsAmateur || b.IsAmateur) // common logic
return false;
return true;
}
}

我应该把“公共(public)逻辑”(如代码中的注释)放在哪里,这样它就在一个地方(例如,作为一个 Func)并且不需要为多个实现重复(如上例)?

请注意,上面的示例非常简单,但现实生活中的“通用逻辑”更为复杂,并且 Foo() 方法做了一些有用的事情!

我希望这个问题很清楚(并且没有在其他地方得到回答 - 我确实进行了搜索)但如果需要,请随时询问我以获取更多详细信息。

最佳答案

在一个普通的抽象类中:

public interface IFoo
{
bool Foo(Person a, Person b);
}

public abstract class FooBase : IFoo
{
public virtual bool Foo(Person a, Person b)
{
if (a.IsAmateur || b.IsAmateur) // common logic
return true;
return false;
}
}

public class KungFoo : FooBase
{

}

public class KongFoo : FooBase
{
public override bool Foo(Person a, Person b)
{
// Some other logic if the common logic doesn't work for you here
}
}

关于c# - 在哪里放置实现相同接口(interface)的多个类所需的通用逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12619409/

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