gpt4 book ai didi

c# - C# 接口(interface)可以要求或规定特定的类吗?

转载 作者:太空狗 更新时间:2023-10-30 00:19:26 25 4
gpt4 key购买 nike

我能否声明一个接口(interface)(即 IMySpecialControl),要求实现它的类也继承自某些基类(即 System.Windows.Controls.UserControl)?

我的想法是,不,这是不可能的。但是,以这样一种方式编写客户端代码真的很好,它只需要一个“IMySpecialControl”,它定义了它关心的几个成员,并且它可以指望该对象也是一个 UserControl,然后它可以添加到 GUI 或操作.

我知道我总是可以检查定义为“IMySpecialControl”的对象实例是否也是一个 UserControl,但我希望 .Net 中可能有一些我不知道的巧妙技巧。 :-)

最佳答案

Can I declare an Interface (i.e. IMySpecialControl) that requires classes implementing it to also inherit from some base class (i.e. System.Windows.Controls.UserControl)?

不,C# 中没有任何内容定义它。

创建 UserControl 的抽象子类可能是最简单的。

可以做的是拥有一个泛型方法或类型,并限制类型参数实现接口(interface)并与类兼容:

public void Foo<T>(T control) where T : UserControl, IMySpecialControl

我不知道这对您的特定情况是否有帮助,但这是您最接近原始要求的方法。

关于c# - C# 接口(interface)可以要求或规定特定的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501789/

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