简体   繁体   中英

C#-Warning 2 Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

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

Session["LoginType"]更改为Session["LoginType"].ToString()

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] 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.

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.

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 .

you can also cast to string:

(string)Session["LoginType"] == "Admin"

This is how the example is done in the Documentation Reading Values From Session State

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM