2014-12-05 99 views
0

晚上好,我的問題是與以下幾點:C#爲模板的結構:無法隱式轉換

public struct vector2D<T1> 
{ 
    public T1 m_w; 
    public T1 m_h; 

    // Irrelevant stuff removed (constructor, other overloader's) 

    public static bool operator !=(vector2D<T1> src, T1 dest) 
    { 
     return (((dynamic)src.m_w != (dynamic)dest) || ((dynamic)src.m_h != (dynamic)dest)); 
    } 

    public static bool operator ==(vector2D<T1> src, T1 dest) 
    { 
     return (((dynamic)src.m_w != (dynamic)dest) || ((dynamic)src.m_h != (dynamic)dest)); 
    } 

    public static bool operator !=(vector2D<T1> src, vector2D<T1> dest) 
    { 
     return (((dynamic)src.m_w != (dynamic)dest.m_w) || ((dynamic)src.m_h != (dynamic)dest.m_h)); 
    } 

    public static bool operator ==(vector2D<T1> src, vector2D<T1> dest) 
    { 
     return Equals(src, dest); 
    } 
} 

現在,我得到了錯誤的是:

Error 1 Operator '!=' cannot be applied to operands of type 'vector2D<int>' and 'vector2D<uint>' 
Error 2 Cannot implicitly convert type 'vector2D<uint>' to 'vector2D<int>' 

現在我知道的編譯器不知道如何「鑄」與下面的代碼片段:

vector2D<uint>[] Something = new vector2D<uint>[2]; // Pretend it has values... 
Dictonary<uint, vector2D<int>> AnotherThing = new Dictonary<uint, vector2D<int>>(); // Pretend it has values... 

if (AnotherThing[0] != Something[0]) { ... } 

AnotherThing[0] = Something[0]; 

我試過幾件事,只是他們要麼給我更多錯誤,不工作或不工作。所以我的問題是我將如何去做「鑄造」?

也可能不錯,我通常使用C++編程,所以C#讓我感到驚訝了好幾次。如果上面的代碼給你做惡夢,還提前抱歉。

回答

2

你需要告訴編譯器如何將類型轉換 '的Vector2D < UINT>' 到 '的Vector2D < int>的'

public static implicit operator vector2D<T1>(vector2D<uint> src) 
     { 
      return new vector2D<T1> 
       { 
        m_h = (T1)Convert.ChangeType(src.m_h, typeof(T1)), 
        m_w = (T1)Convert.ChangeType(src.m_w, typeof(T1)), 
       }; 
     } 
+0

謝謝你,就像一個魅力。我嘗試了類似的東西,但沒有奏效,我明白爲什麼它沒有,反正再次感謝你。 – SharkBytes 2014-12-05 03:26:57