代码之家  ›  专栏  ›  技术社区  ›  Will Marcouiller

这怎么可能不相等呢?

  •  2
  • Will Marcouiller  · 技术社区  · 14 年前
    1. 我的目标:从Excel中提取一个值 Range ,并验证这些单元格的值在此范围内是否相同;
    2. 当一个单元格的值与另一个单元格的值不同时,我需要返回空值。

    这是一段代码:

    internal object GetValueFromCells(string start, string end, Formats format) {
        // Verifying for empty or null parameters here and throwing accordingly...
    
        try {
            Range cells = Excel.get_Range(start, end) as Range;
    
            object value = null;
            bool sameValue = false;
    
            foreach(Range cell in cells) {
                // This condition block shall execute only once, since 'value' shall not be null afterwards.
                if (value == null || value == DBNull.Value)
                    if (Formats.Formated == format) {
                        value = cell.Text;
                        // The following results to be false !?...
                        sameValue = value == cell.Text; // Shall this not be true?
                    } else {
                        value = cell.Value2;
                        // The following results to be false !?...
                        sameValue = value == cell.Value2; // Shall this not be true?
                    }
    
                // This results being always false!?...
                // Shall this not be true, I wonder?
                sameValue = Formats.Formated == format ? value == cell.Text : value == cell.Value2; 
    
                if(!sameValue)
                    return null;
            }
    
            return value;
        } catch (Exception ex) {
            // Exception handling...
        }
    }
    

    在阅读这段代码时,我谦虚地期望当范围内的所有单元格都具有相同的值(例如334)时返回一个值。

    但是,此方法始终返回空值(在Visual Basic中为零)!

    任何人都可以解释我在这里遗漏了什么,而这:

    value == cell.Value2
    

    总是回报 ?

    也许是我的算法不对吧?

    编辑第1页

    这解决了问题:

    sameValue = Formats.Formatted == format ? cell.Text.Equals(value) : cell.Value2.Equals(value);
    

    我接受了@jerod houghtelling的回答,因为他的回答建议使用toString()和equals()方法来解决问题。

    除此之外,我不喜欢调用toString()方法,因为值可以是数字,比较字符串下的数字对我来说很奇怪。所以我更喜欢我在解决方案中采用的equals()方法。

    我要感谢@sir gallahad和@jerod houghtelling,感谢他们的回答。这是我第一次不得不面对这样的情况,他们都帮助我更好地了解了在幕后发生的事情,以及其他通过评论做出贡献的人。

    感谢那些反对我问题的人。这是为了证明我不是那么愚蠢的要求!= P和合和…

    2 回复  |  直到 14 年前
        1
  •  3
  •   Jerod Houghtelling    14 年前

    我猜是吧 cell.Value2 每次调用对象时都返回该对象的新实例。因此我可以推断 == 正在检查公式两边是否都是对象的同一个实例。要实际比较存储在两侧的值,必须使用 .Equals 或者将值转换为可比较的值,例如字符串。

    sameValue = value.Equals( cell.Value2 ); 
    /* or */
    sameValue = value.ToString() == cell.Value2.ToString();
    

    我也不明白 value 以你的例子为例。

        2
  •  3
  •   Andre Vianna    14 年前

    大概是 value == cell.Value2 正在比较来自不同实例的对象。

    尝试 value.ToString() == cell.Value2.ToString()