相关疑难解决方法(0)

盒装价值类型比较

我在这里想要实现的是盒装基元类型的直接值比较.

((object)12).Equals((object)12); // Type match will result in a value comparison,
((object)12).Equals((object)12d); // but a type mismatch will not. (false)
object.Equals((object)12,(object)12d); // Same here. (false)
Run Code Online (Sandbox Code Playgroud)

我理解'为什么'.我只是没有看到'怎么样'.

这些类型在运行时之前是未知的,它们可以是来自数据源的任何基本类型.这包括字符串,日期时间,bool等等.我已经走下了编写扩展方法的丑陋路线,该方法可以解决两种类型,然后在进行'=​​='比较之前进行转换:(为了完整性,我包括了每种基本类型,加上我感兴趣的那些)

public static bool ValueEquals(this object thisObj, object compare)
    {
        if (thisObj is int)
        {
            int obj = (int)thisObj;
            if (compare is int)
                return (obj == (int)compare);
            if (compare is uint)
                return (obj == (uint)compare);
            if (compare is decimal)
                return (obj == (decimal)compare);
            if (compare is float)
                return (obj == (float)compare);
            <... and so …
Run Code Online (Sandbox Code Playgroud)

c# reflection boxing unboxing value-type

12
推荐指数
1
解决办法
3548
查看次数

标签 统计

boxing ×1

c# ×1

reflection ×1

unboxing ×1

value-type ×1