Distinguish a string literal from a string C#

前端 未结 2 413
孤城傲影
孤城傲影 2021-01-26 05:43

I want to do something like

IsItAStringLiteral(\"yes\")
var v = \"no\";
IsItAStringLiteral(v)

With the obvious return value. Is it possible?

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-26 06:08

    No. You won't be able to tell whether a string is a literal or not.

    The simple reason: Literals, string variables, interned strings of all kinds....each one is a reference to a System.String. And all strings, when passed by value, are loaded onto the stack prior to the function call that uses them (and thus, are unrelated to the name of any variable that references them). By the time the function is called, a literal and a variable look exactly the same, and will be treated exactly the same when passed by value.

    The only way that might be possible is some unsafe stuff that might check the address of the object. If the address is within an assembly's address space, it almost certainly came from a constant of some sort. But that's unreliable (as strings set to literals would look just like the literals), extremely hackish, ugly, and above all unnecessary for any purpose that i can think of.

    You should probably reconsider how you're doing whatever you're doing, if you have to care whether a string is a literal or not.

提交回复
热议问题