C# 通用扩展方法装箱转换问题

标签 c# generics boxing

我正在致力于在 C# 中迁移/重写一些 Java 泛型。我收到一个我不明白的错误。

(这在一定程度上是一个基于组合而非继承的实验,旨在限制不需要某些功能的子类的膨胀,但这也只是一个更好地理解 C# 泛型的实验。)

注意:实际的子类实现实际上按照我的预期工作,只是扩展方法未编译。

父类:

public abstract class PageObject<T> where T : PageObject<T>
{

    protected IWebDriver WebDriver => ServiceLocator.GetWebDriver();

    public PageObject()
    {
        PageFactory.InitElements(WebDriver, this);
    }

    // ... more stuff, but the constructor is the important thing that keeps
    // me using an abstract parent class. There are some abstract methods
    // that return T so the child classes can return "this" in a fluent api.
}

接口(interface):

public interface IHasCustomLoadCondition<T> where T : PageObject<T>
{
    bool IsLoaded();
}

和一个扩展方法,这是发生错误的地方:

public static T WaitForCustomPageLoad<T>(this T page) where T : IHasCustomLoadCondition<T>
{
    wait.Until<bool>((d) =>
    {
        return page.IsLoaded();
    });
    return page;
}

错误信息:

The type 'T' cannot be used as type parameter 'T' in the generic type or method
'IHasCustomLoadCondition<T>'. There is no boxing conversion or type parameter conversion
from 'T' to 'PageObject<T>'.

最佳答案

既然您有此声明:

public interface IHasCustomLoadCondition<T> where T : PageObject<T>
                                            ^---------------------^

您必须确保也将此约束带入派生接口(interface),实现在同一 T 上也是通用的类和方法,因此此方法:

public static T WaitForCustomPageLoad<T>(this T page) where T : IHasCustomLoadCondition<T>

还必须有这个约束:

public static T WaitForCustomPageLoad<T>(this T page)
    where T : PageObject<T>, IHasCustomLoadCondition<T>

基本上:

public static T WaitForCustomPageLoad<T>(this T page) where T : IHasCustomLoadCondition<T>
                                      ^                                                 ^
                                      |                                                 |
                                      +-------- constraints must be compatible ---------+

关于C# 通用扩展方法装箱转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39285928/

相关文章:

c# - 如何在不装箱的情况下存储不同类型的结构

c# - 当表使用标识列并且您需要匹配任意键时,如何使用 ms 同步框架同步数据库

c# - 我可以在 .NET 中像数字一样格式化字符串吗?

c# - Xlinq 查询返回 nullWhereEnumerableIterator<>

java - 如何插入不使用旋转的 AVL 树?

java - 接口(interface)中的嵌套参数化类型

c# - 自定义验证唯一属性 - 泛型类

java - 将 Collections.emptyMap 作为参数传递时出现错误

c# - 为什么结构需要装箱?

java - java中的包装器和自动装箱/拆箱有什么区别?