只是想知道是否还有代表C#3.5中的以下代码:

public struct Foo<T> {

    public Foo(T item) {
        this.Item = item;
    }

    public T Item { get; set; }

    public static explicit operator Foo<U> ( Foo<T> a )
        where U : T {

        return new Foo<U>((U)a.Item)
    }
}

由于

有帮助吗?

解决方案

转换运算符不能是通用的。从规范部分10.10开始,这是convert-operator-declarator的格式:

conversion-operator-declarator:
    implicit   operator   type   (   type   identifier   )
    explicit   operator   type   (   type   identifier   )

比较一下方法标题:

  

方法的头的:   属性 opt method-modifiers opt partial opt 返回型的   会员名称 type-parameter-list opt formal-parameter-list opt )   型参数约束子句<子>选择

(抱歉格式化 - 不知道如何做得更好。)

请注意,运算符格式不包含类型参数列表或类型参数约束。

其他提示

您的代码归结为以下行:return new Foo<U>((U)a.Item)

您尝试将基类分配给继承的类,这是不可能的。

假设T(基类)的类型为Stream且U的类型为MemoryStream(继承的类),则不能将<=>指定给类型为<=>的变量。

我认为简短的回答是<!>“不可能。尝试使用方法代替<!>“;

似乎也是这个问题的愚蠢 .NET泛型中重载运算符约束的解决方案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top