C# 模板化结构:无法隐式转换

本文关键字:转换 结构 | 更新日期: 2023-09-27 18:33:07

晚上,我的问题出在以下几点:

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# 让我感到惊讶了几次。如果上面的代码让你做噩梦,也提前道歉。

C# 模板化结构:无法隐式转换

你需要

告诉编译器如何将类型'vector2D'转换为'vector2D'

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