c# - C#模板化结构: Cannot implicitly convert

标签 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#使我感到有些惊讶。如果上述代码给您带来噩梦,也请您提前表示歉意。

最佳答案

您需要告诉编译器如何将类型'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)),
                };
        }

关于c# - C#模板化结构: Cannot implicitly convert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27307934/

相关文章:

c# - Ionic.Zip ArgumentException(已添加具有相同键的项目)

gcc - 我的代码适用于 gcc 4.6,但不适用于 gcc 4.7(或更高版本)

c++ - 将 typeid().hash_code() 存储为 16 位整数

C:未定义的行为事实

c# - 避免使用 NHibernate 实体列表进行 N+1 选择

c# - Azure 上的 HttpRuntime.AppDomainAppPath

javascript - Json参数转换继承Web api 2

react-native - 在react-native运行android时生成错误

c++ - 代码在 Visual Studio 2010 中编译但根本不应该编译

javascript - 如何在 JavaScript 中将数字的二进制表示形式从字符串转换为整数?