简体   繁体   English

在C#中是否可以通过以下方式重载通用强制转换操作符?

[英]Is it possible in C# to overload a generic cast operator in the following way?

Just wondering if there is anyway to represent the following code in C# 3.5: 只是想知道是否还有代表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)
    }
}

Thanks 谢谢

Conversion operators can't be generic. 转换运算符不能是通用的。 From the spec section 10.10, here's the format of a conversion-operator-declarator: 从规范部分10.10开始,这里是转换操作符声明符的格式:

 conversion-operator-declarator : conversion-operator-declarator\n    implicit operator type ( type identifier ) 隐式运算符类型类型 标识符\n    explicit operator type ( type identifier ) 显式运算符类型类型 标识符 

Compare this with, say, a method-header: 比较一下,比较一个方法标题:

method-header : attributes opt method-modifiers opt partial opt return-type member-name type-parameter-list opt ( formal-parameter-list opt ) type-parameter-constraints-clauses opt method-headerattributes opt method-modifiers opt partial opt return-type member-name type-parameter-list optformal-parameter-list opttype-parameter-constraints-clauses opt

(Sorry about the formatting - not sure how to do it better.) (抱歉格式化 - 不确定如何做得更好。)

Note that the operator format doesn't include a type parameter list or type parameter constraints. 请注意,运算符格式不包括类型参数列表或类型参数约束。

Your code boils down to the line: return new Foo<U>((U)a.Item) 你的代码归结为这一行: return new Foo<U>((U)a.Item)

Where you try to assign a baseclass to an inherited class, which is impossible. 在哪里尝试将基类分配给继承的类,这是不可能的。

Let's say T (base-class) is of type Stream and U is of type MemoryStream (inherited class), you cannot assign a Stream to a variable of type MemoryStream . 假设T(基类)是Stream类型而U是MemoryStream类型(继承类),则不能将Stream分配给MemoryStream类型的变量。

I think the short answer is "Not possible. Try using a method instead" 我认为简短的回答是“不可能。尝试使用方法”

Also seems to be dupe of this question Solution for overloaded operator constraint in .NET generics 似乎也是这个问题的愚蠢解决方案在.NET泛型中重载操作符约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM