C#Templated Struct:无法隐式转换

时间:2014-12-05 02:47:39

标签: c# compiler-errors type-conversion operator-overloading

晚上,我的问题是:

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#让我感到惊讶几次。如果以上代码让您做恶梦,也提前抱歉。

1 个答案:

答案 0 :(得分:2)

你需要告诉编译器如何转换类型'vector2D&lt; uint&gt;'到'vector2D&lt; int&gt;'

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)),
                };
        }