gpt4 book ai didi

c# - 接口(interface)中的类型约束适用于基类

转载 作者:太空狗 更新时间:2023-10-29 21:40:15 24 4
gpt4 key购买 nike

我有一个基类,它定义了这样一个泛型方法:

public class BaseClass
{
public T DoSomething<T> ()
{ ... }
}

由于这个类是第三方的,没有接口(interface),所以我定义了一个接口(interface)来定义该类中实际需要的方法。这样我就得到了松散的耦合,实际上可以将第三方类与其他东西交换。对于此示例,请考虑以下接口(interface):

public interface ISomething
{
T DoSomething<T> ()
where T : Foo;
}

如您所见,它定义了相同的方法,但还在类型参数上应用了类型约束,该类型参数来自与此无关的一些其他要求。

接下来,我定义了 BaseClass 的子类型,它也实现了 ISomething。此类将用作接口(interface)背后的通常实现——而接口(interface)将是应用程序的其余部分将要访问的内容。

public class Something : BaseClass, ISomething
{
// ...
}

由于BaseClass中的DoSomething已经支持任何类型参数T,它应该特别支持的子类型类型参数>富。所以人们会期望 BaseClass 的子类型已经实现了该接口(interface)。但是我收到以下错误:

The constraints for type parameter 'T' of method 'BaseClass.DoSomething()' must match the constraints for type parameter 'T' of interface method 'ISomething.DoSomething()'. Consider using an explicit interface implementation instead.

现在,我有两种可能性;第一个是按照错误提示执行操作并明确实现接口(interface)。第二种是使用 new 隐藏基本实现:

// Explicit implementation
T ISomething.DoSomething<T> ()
{
return base.DoSomething<T>();
}

// Method hiding
public new T DoSomething<T>()
where T : Foo
{
return base.DoSomething<T>();
}

两者都有效,但我可能更喜欢第二种解决方案,以保持类本身可以访问该方法。但是它仍然留下以下问题:

当基类型已经使用不太严格(读取:无)类型约束实现它时,为什么我必须重新实现该方法?为什么该方法需要完全按原样实现?

编辑:为了赋予该方法更多意义,我将返回类型从 void 更改为 T。在我的实际应用中,我既有泛型参数也有返回值。

最佳答案

尝试使用组合而不是继承来实现Something:

public class Something : ISomething
{
private readonly BaseClass inner = ...;

void DoSomething<T>() where T : Foo
{
inner.DoSomething<T>();
}
}

关于c# - 接口(interface)中的类型约束适用于基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14607310/

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