Distinguish a string literal from a string C#

我与影子孤独终老i 提交于 2019-12-02 07:31:24

You can use the string.IsInterned method to determine whether a given string is in the .NET intern pool. All string literals are automatically added to the intern pool before the application begins running.

Of course, that won't help you with your exact question. Variable 'v' will reference a string literal, so it too will appear in the intern pool. Why do you need such functionality?

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!