代码之家  ›  专栏  ›  技术社区  ›  Graham

比较对象是否包含字符串或int

c#
  •  -2
  • Graham  · 技术社区  · 8 年前

    object . 它们可能包含int或string,但始终都是同一类型。

    我知道我可以像这样测试平等:

    if (a.Equals(b))
        ...
    

    但我该怎么做呢

    if (a > b)
        ...
    
    if (a < b)
        ...
    

    对象 没有 compareTo

    测试代码:

    int i1 = 7;
    int i2 = 12;
    
    int result = compareValues((object)i1, (object)i2);
    
    string s1 = "abcd";
    string s2 = "efg";
    
    int result = compareValues((object)s1, (object)s2);
    
    ...
    
    public int compareValues((object)a, (object)b)
    {
        if (a.Equals(b))
            return 0;
    
        if (a < b)
            return -1;
    
        return 1;
    }
    

    编辑

    对象 . 测试脚本纯粹用于测试。

    3 回复  |  直到 8 年前
        1
  •  3
  •   Ehsan Sajjad    8 年前

    这是我的提议。你检查这个值是否可比( int 和 string 如果是,将它们转换为 IComparable 和使用 CompareTo

    fiddle 作品

    public static int CompareValue(object a, object b)
    {
        return (a as IComparable).CompareTo(b as IComparable);      
    }
    
        2
  •  2
  •   Patrick Hofman Wahid Bitar    8 年前

    在我看来,你应该先检查数据类型。你永远不知道你是不是搞砸了。(这正是这个设计的问题所在,难道你不能做得更安全一点吗?)

    if (a is int ai && b is int bi)
    {
        // now compare ai en bi
        return ai.CompareTo(bi);
    }
    else if (a is string astr && b is string bstr)
    {
        // now compare astr en bstr
        return astr.CompareTo(bstr);
    }
    else
    {
        // a or b is null or have different types.
    }
    
        3
  •  -4
  •   Rob    8 年前

    CompareTo 方法。。。你要么就用它,要么就把你的智力投给它。

    GetType() 对象的