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

前端 未结 3 1664
孤独总比滥情好
孤独总比滥情好 2020-12-16 12:35

Just wondering if there is anyway to represent the following code in C# 3.5:

public struct Foo {

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


        
相关标签:
3条回答
  • 2020-12-16 13:15

    Conversion operators can't be generic. From the spec section 10.10, here's the format of a conversion-operator-declarator:

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

    Compare this with, say, a method-header:

    method-header: attributesopt method-modifiersopt partialopt return-type member-name type-parameter-listopt ( formal-parameter-listopt ) type-parameter-constraints-clausesopt

    (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.

    0 讨论(0)
  • 2020-12-16 13:16

    Your code boils down to the line: 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.

    0 讨论(0)
  • 2020-12-16 13:26

    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

    0 讨论(0)
提交回复
热议问题