字符串比较 - 带字符串的对象

时间:2013-11-11 12:42:15

标签: c#

看看这些家伙:

从VisualStudio中的立即窗口输出。

"15" == x.Documents.Attributes["key"]
false
x.Documents.Attributes["key"]
"15"

当两个值相等时为什么为假?

属性是Dictionary<string, object> ......没什么特别的。

我不明白。我以为==知道如何使用object.ToString()来处理字符串。

我想念的是什么人?帮助我解决这个问题。

6 个答案:

答案 0 :(得分:4)

因为该值仅称为object==实际上是此处的引用相等性检查。要执行string测试,编译器需要知道它是string

"15" == (string)x.Documents.Attributes["key"]

这是因为像==这样的运算符重载,而不是重写 - 它们不是多态的。

如果值不是所有字符串,则更安全:

"15" == x.Documents.Attributes["key"] as string

因为如果返回的值实际上不是asnull将返回string(此处==null值很好。< / p>

答案 1 :(得分:2)

答案很简单:您正在获取一个Object类型的密钥,并将其与string进行比较。尝试在您获得的密钥上调用ToString(),然后您将获得正确的比较,从而获得true

答案 2 :(得分:2)

如果你要比较对象,(就像你的情况一样),通常最好使用Equals方法而不是==运算符,因为它将调用正确的实现。

代码:

x.Documents.Attributes["key"].Equals("15");

应该返回true

编辑:仅当您的类型实际上是字符串时才会成立。如果你想检查你的对象的字符串表示是否与其他字符串表示相匹配,你应该像其他人所说的那样做:

x.Documents.Attributes["key"].ToString() == "15";

那就是说,我不会推荐它。如果对象没有ToString(),您只需检查它们是否为同一类型(Object的{​​{1}}实现)。在这一点上,这取决于你想要做什么......

答案 3 :(得分:0)

第一行:x.Documents.Attributes["key"]

第二行:x.DocumentFile.Attributes["key"]

看到区别?

答案 4 :(得分:0)

你应该使用equals并输入强制转换为字符串

"15".equals( 
    (string) x.Documents.Attributes["key"])
    false
    x.Documents.Attributes["key"]
    "15"

答案 5 :(得分:0)

Marc Gravell的回答绝对正确,只是补充一下,这里有一个例子:

var dic = new Dictionary<string, object>
{
    {
        "key",
        string.Format("{0}", "hello") // this to avoid interning string
    }
};
Console.WriteLine(dic["key"] == "hello"); // false
Console.WriteLine((string)dic["key"] == "hello"); // true
相关问题