C#string数组作为参数的疑问 分解一行字符串

来源:百度知道 编辑:UC知道 时间:2024/06/14 16:06:14
public class Program
{
public int StringSplit(string s, char[] separtor, string[] tempFileds)
{
s.Trim();
tempFileds = s.Split(separtor);

//for (int i = 0; i < tempFileds.Length; i++)
//{

// p.CopyTo(tempFileds ,i);
// Console.WriteLine("0", tempFileds[i]);

//}
return tempFileds.Length;

}
static void Main(string[] args)
{
string myString = "D10,图斑,Polygon,DLTB";
char[] split = {','};
int n;
string[] tempFileds =new string [10] ;

Program c=new Program() ;
n=c.StringSplit (myString, split, tempFileds);

for(int i=0;i<n ;i++)
{

Console.WriteLin

我给你解释下为什么吧
把你的StringSplit换个形式表现如下:
public int StringSplit(string s, char[] separtor, string[] tempFileds)
{
s.Trim();
string[] temp = s.Split(separtor);
tempFileds = temp;//我标记这行
return temp.Length;

}

我们知道数组传的是引用,即tempFileds中存放的是数组的地址,我们把这个地址完全的当做是一个整数吧(其本身就是个32位的整数),那么tempFileds现在存的是个整数了。现在看我标记的这行,tempFileds里面存放的整数被改变了,注意了只是它的里面存放的地址被改变了,而不是它引用的对象发生了改变。
上面的整个过程相当于把一个int型变量传给了函数,再在函数里面改变了这个int型变量的值,想当然,对调用这个函数的函数是没有影响的。

tempFileds的地址被改变后,对原来它所引用的对象没有任何关系了,井水不犯河水

解决办法就是一楼的方法。把引用变量本身按引用传递过去,这样传过去后,StringSplit函数体执行完后,tempFileds和刚开始定义的那个tempFileds所引用的对象,根本就没有关系了。
你可以在Main函数执行完StringSplit后测试下tempFileds的长度根本不是10了,等于说你的初始化没有任何作用。你可以使用out参数传递引用

这个当然不行了啊
函数这样定义
public int StringSplit(string s, char[] separtor, ref string[] tempFileds)

这样调用
Program c=new Program() ;
n=c.StringSplit (myString, split, ref tempFileds);