【问题标题】:C# Concrete Class Inheriting from Closed Constructed Type从封闭构造类型继承的 C# 具体类
【发布时间】:2018-07-29 16:14:01
【问题描述】:

我有一个Generic interface 声明Generic Method,如下所示。

 public interface BaseInterface<T> where T: class
    {
        //This will not generate the compile time
        //warning that the type parameter of method is same as interface
        U Method1<U>(U u) where U : T;

    }

现在我定义了一个新的Concrete类,继承了上面接口的一个closed constructed type

public class DerivedClass : BaseInterface<string>
    {

        U BaseInterface<string>.Method1<U>(U u)
        {
            return "Some String";
        }
    }

在界面中,我使用了对类型参数U的约束为where U : T。我还使用了T is string 的封闭构造类型。那么在DerivedClass 中,为什么编译器不让我返回string

错误

错误 CS0266 无法将类型“字符串”隐式转换为“U”。存在显式转换(您是否缺少演员表?) GenericPractice

【问题讨论】:

  • 为什么不用U Method1&lt;U&gt;() where U : T; 而只是做T Method1()
  • 我希望 Method1 在类型参数上的工作与类的相同。
  • 我现在稍微修改了接口定义。
  • 想象一下你使用了 BaseInterface,当 U 是 StreamReader 时,你将无法返回 new object()...
  • 另外,当 T 是一个字符串时,你期望 U 是什么?字符串被密封。为什么不返回 T?

标签: c# generics inheritance


【解决方案1】:

您收到错误的原因是因为编译器没有检查您指定为 T 的类是否是密封的,然后意识到因为 U : T 意味着 U 必须是 T。如果 T 不是密封的,则代码永远无法工作,因为任何类都可以继承 T,并且您无法在没有代码的情况下在派生类型之间进行转换。

但根据您的 cmets,我认为您可能只是在寻找这个:

public interface BaseInterface<T> where T: class
{
    T Method1<U>(U u) where U : T;
}

public class DerivedClass : BaseInterface<string>
{
    string BaseInterface<string>.Method1<U>(U u)
    {
        return "Some String";
    }
}

请查看上面的代码: https://dotnetfiddle.net/aARD4W

【讨论】:

  • 这也给了我派生类没有实现BaseInterface的错误
  • 请查看答案中的链接,该链接显示代码有效。
  • 对不起。我没有替换U到T接口中Method1的返回类型,我只是试着理解你的解释
【解决方案2】:

为什么不简单地这样做呢?因为在您的代码中,UT

public interface BaseInterface<T> where T : class
{
    T Method1(T u);
}

public class DerivedClass : BaseInterface<string>
{
    public string Method1(string u)
    {
        return "Some String";
    }
}

您不需要where U : T,因为您可以使用T,并且由于UT,那么Method1 也不需要是通用的,因为我们知道它将返回什么类型/需要。

在这里测试:https://dotnetfiddle.net/yFyZtc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多