软讯网络 > 编程语言 > .NET > C#.NET > More on "More on Strings"
【标 题】:More on "More on Strings"
【关键字】:
More,on,More,on,Strings
【来 源】:http://blog.joycode.com/qqchen/archive/2004/08/23/31344.aspx
More on "More on Strings"
贴了关于.NET String Immutable和Implementaion的blog,收到下面两个回复:
- 对于定义如 public void xx(string yy);的函数,传进去的yy的值是改不了的.
下面的程序展示了如何在Native函数中修改字符串参数的值:
//Native.cpp: the exported native dll function
extern "C" _declspec(dllexport) void _stdcall ModifyString(LPWSTR str) {
str[0] = L'X';
}
//Test.cs: Csharp function:
[DllImport(“Native.dll”, CharSet=CharSet.Unicode)]
public static extern void ModifyString(string str);
public static void Main() {
string str = “Hello, World”;
ModifyString(str);
Console.WriteLine(str);
}
这里的关键是Unicode,.NET String的内部编码是UCS2,如果Native函数参数恰好用的是UCS2,出于性能考虑,CLR会直接把string内部字符串的地址传给Native;如果Native函数接受ASCII编码,CLR就不得不做一个拷贝了。
- Hash算法从来都不保证不同的值生成的Hash值不同!
正是因为散列函数可能出现冲突,所以在散列查找之后还必须比较键值以确定查找的正确性,所以一旦加入Hashtable,对象的键值是不能改变的。下面的程序用CLR内部的InternTable来展示改变一个Intern字符串的结果:
static unsafe void ModifyConst() {
string str = "Hello";
fixed(char* pstr = str) {
pstr[0] = 'X';
}
}
static void Main() {
ModifyConst();
StringBuilder sb = new StringBuilder("Hel");
sb.Append("lo");
string str = sb.ToString();
Console.WriteLine(str);
switch(str) {
case "Xello":
Console.WriteLine("string is Xello"); break;
case "Hello":
Console.WriteLine("string is Hello"); break;
default:
Console.WriteLine("Not Found"); break;
}
}
不妨猜猜看程序的输出是什么。(Warning: Think at your own risk. Potential side effects include dry mouth, sleepless and mind blow). :)