C#-Warning 2 可能的非预期引用比较;要进行值比较,请将左侧强制转换为“字符串" [英] C#-Warning 2 Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

查看:37
本文介绍了C#-Warning 2 可能的非预期引用比较;要进行值比较,请将左侧强制转换为“字符串"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if ((Session["UserName"] != null && Session["LoginType"] == "Admin") || (Session["UserName"] != null && Session["LoginType"] == "Employee"))
{ 
    TotalMarketBalance();
}

推荐答案

我建议将 if 语句更改为:

I suggest to change the if-statement to this:

if (Session["UserName"] != null && 
     (Session["LoginType"] as string == "Admin" || 
      Session["LoginType"] as string == "Employee")
   )

Session[string key] 返回一个 object.如果你使用 == 将一个 object 与某个东西进行比较,你就进行了一个 引用比较.并且字符串文字(例如"Admin")永远不会像那个对象一样拥有相同的引用,即使这个对象一个字符串.

Session[string key] returns an object. And if you compare an object to something using ==, you do a reference comparison. And the string literal ("Admin" for example) will never have the same reference like that object, even if this object is a string.

通过将 object 转换为 string,编译器知道它必须调用 string 的相等方法,该方法比较字符串的内容而不是参考.

By casting the object into a string, the compiler knows that it has to call the equality methods of string, which compare the string's contents instead of their references.

当然,您也可以进行直接转换 ((string)Session["LoginType"]) 或调用 ToString().但是如果(出于某种奇怪的原因)返回对象是不是一个字符串,则第一个将抛出异常.如果(出于某种奇怪的原因)该值仍然是 null,则第二个将抛出 NullReferenceException.

Of course you can do a direct cast ((string)Session["LoginType"]) or call ToString(), too. But the first will throw an exception if (for some strange reason) the return object is not a string. The second will throw a NullReferenceException if (for some strange reason) the value is still null.

这篇关于C#-Warning 2 可能的非预期引用比较;要进行值比较,请将左侧强制转换为“字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆