gpt4 book ai didi

C# 将旧接口(interface)函数携带到新接口(interface)

转载 作者:行者123 更新时间:2023-11-30 15:01:56 24 4
gpt4 key购买 nike

之前也有人问过类似的问题,但是找不到这样的答案。

C#

public interface I1 { //sealed interface, cannot change
string Property1 {get; set;}
void OnEvent();
}
public class C1 : I1 {//sealed class, cannot change
public string Property1 {get; set;}
public virtual void OnEvent() {/*update property1...*/}
}
public class C2 : C1 {//my class inherits C1. Now I want I2 for my class C2
public string Property2 {get; set;}
public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}

如何获得包含可以传递的 Property1Property2 的接口(interface)“I2”?

最佳答案

您似乎正在尝试做一些接口(interface)不适合做的事情。接口(interface)只是一个契约,当一个类实现该契约时,它 promise 它将以某种方式实现它,但接口(interface)本身不关心,因为它不关心本身带有实现细节。如果你想将行为传递给 child ,你需要子类化。

但是,如果您真的想创建一个从父界面“承载功能”的界面,那绝对是受支持的并且很容易实现。您需要做的就是创建一个子接口(interface)来继承您的父接口(interface)。

例子:

interface IParentInterface
{
int FirstProperty {get;set;}
void OnChange();
}

interface IChildInterface: IParentInterface
{
string SecondProperty {get;set;}
}

class InterfaceInheritanceGoodness: IChildInterface
{
public int FirstProperty { get; set; }

public string SecondProperty { get; set; }

public void OnChange()
{
throw new NotImplementedException();
}
}

而且,接口(interface)支持多重继承......玩得开心!

关于C# 将旧接口(interface)函数携带到新接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13319553/

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