我正在致力于在 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/