How to realize explicit and implicit type conversion for non-generic synonyms of generic struct?

StackOverflow https://stackoverflow.com/questions/16912582

문제

I have a generic struct and two synonyms with defined generic type parameter. I want to define type conversions between these two types like this:

using X = A<int>;
using Y = A<long>;

struct A<T>
{
    private T data;

    public A(T data)
    {
        this.data = data;
    }

    public static explicit operator X(Y value)
    {
        return new X((int)value.data);
    }
    public static implicit operator Y(X value)
    {
        return new Y(value.data);
    }
}

and here is an example how I want to use the struct:

class Program
{
    static void Main(string[] args)
    {
        X x = new X(1);
        Y y = new Y(2);

        x = (X)y; // explicit cast with precision loss
        y = x; // implicit cast without precision loss
    }
}

Unfortunately each "using" creates new specific definition of the struct and C# compiler treats synonym structures not as a subset of a generic structure, but as an individual structure. That's why compiler reports errors:

  1. "ambigious between X.static implicit operator Y(X) and Y.static implicit operator Y(X)".
  2. "User-defined conversion must convert to or from the enclosing type".

Does anybody knows a way to realize this type conversions without changing type to class?

UPDATE: I'm using .NET 4.

도움이 되었습니까?

해결책

The error

User-defined conversion must convert to or from the enclosing type.

means that your conversion operators need to convert to/from A<T>. Yours are converting to/from A<int/string>. That's not the same thing (much less general at least).

So this cannot work. You have to find some other way to do the conversions. Maybe runtime casting can help here (define the operators as acting on A<T> and do casting inside of them).

I think this problem is unrelated to the type synonyms. In fact they made the question harder to understand.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top