gpt4 book ai didi

C#:用于启用实现和覆盖的接口(interface)和抽象

转载 作者:行者123 更新时间:2023-11-30 19:20:30 32 4
gpt4 key购买 nike

我必须设计大约 5 个不同的类。

这些类的很多部分都非常相似,但它们会有细微的差异(当然)。

如果我编写一个interface,让我设计的每个类都实现,那么interface 中的每个abstract 方法都必须完整地编写。

如果我编写一个 base 类,我的每个设计类都派生自该类,那么每个类将自动在我在 base 类,但它们都需要被覆盖,调用 base 功能,以包含细微的差异。

有没有办法结合这些功能?我喜欢要求实现接口(interface)的方法,但我也喜欢设置由base 类预编程的功能。

我在这里和其他地方看过很多例子,但看起来没有人按照我描述的去做。有可能吗?

编辑:因此,鉴于此:

abstract class Base
{
virtual protected void OptionallyOverridable() {}
abstract protected void SubclassMustImplement();
}

...有没有办法写出这样的东西:

abstract class Base2
{
DataEventType EventType;
DataChangedEventHandler OnDataChange;

virtual protected void OptionallyOverridable() {}
abstract protected void SubclassMustImplement() {
// values here are guaranteed
}
}

最佳答案

C# 允许一个类既可以继承基类又可以实现接口(interface),那么为什么不两者兼顾呢?

public interface IFoo
{
public void Bar();
public bool Baz();
}

public abstract class BaseFoo : IFoo
{
//fields/properties used in all classes
public void Bar()
{ //Implementation }

public bool Baz()
{ //Implementation }
}

public class DerivedFoo : BaseFoo, IFoo {...}

关于C#:用于启用实现和覆盖的接口(interface)和抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6064047/

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