这怎么可能不相等?

  1. 我的目标:从Excel Range提取一个值,并validation这些单元格的值是否在此范围内相同;
  2. 当一个单元格的值不同于另一个时,我需要返回null。

这是一段代码:

 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)时都会返回一个值。

但是,此方法始终返回null(在Visual Basic中为Nothing)!

任何人都可以解释我在这里错过的东西:

 value == cell.Value2 

总是返回false

也许是我的algorithm不太对吗?

编辑#1

这已经解决了这个问题:

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

我接受了@Jerod Houghtelling的回答,因为他的回答暗示了ToString()和Equals()方法可以解决这个问题。

除此之外,我不喜欢调用ToString()方法,因为值可以是数字,比较string下的数字对我来说看起来很奇怪。 所以我更喜欢我在解决scheme中采用的Equals()方法。

我想感谢@Sir Gallahad和@Jerod Houghtelling的好的答案。 这是我第一次面对这样的情况,他们都帮助我更好地理解发生了什么事情,还有其他人通过评论做出了贡献。

感谢那些高举我的问题的人。 这是为了certificate我并不是那么愚蠢的要求! = P Hehehe …

我猜测, cell.Value2每次调用它时都会返回一个对象的新实例。 因此,我会推断==正在检查,看看方程的两边是对象的相同的实例。 要实际比较两端存储的值,您必须使用.Equals或将值转换为可以比较的值,例如string。

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

我也没有看到你的例子中设置的value

可能value == cell.Value2比较来自不同实例的对象。

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