2012-10-17 97 views
0

调用func1变量后,mydata保持为空。在调试模式下,我发现它在func3中将数据设置为字符串。为什么它在退出功能后没有通过价值?
类例如c#类变量在调用函数后仍然为空

class myclass 
{ 
    public string mydata; 

    public int func1() 
    { 

     //.... 
      func2(/**/, mydata); 
     //.... 
     return 1; 
    } 


    private int func2(/**/,data) 
    { 
     byte[] arr = new byte[1000]; 
      //... 
       func3(arr,data); 
      //... 
     return 1; 
    } 


    private void func3(byte[] arr, string data) 
    { 
     char[] a = new char[100]; 
     //... 

     data = new string(a); 
    } 

} 
+1

因为你是按值传递,而不是参考? –

+5

请阅读http://pobox.com/~skeet/csharp/parameters.html –

回答

1

默认情况下,参数按值传递;这意味着通过的内容实际上是变量的副本(在参考类型如string的情况下是参考的副本)。当func3分配data时,它只会修改变量的本地副本。

现在,如果你改变func2func3签名,这样data通过引用传递,你会得到预期的结果:

public int func1() 
{ 

    //.... 
     func2(/**/, ref mydata); 
    //.... 
    return 1; 
} 


private int func2(/**/,ref string data) 
{ 
    byte[] arr = new byte[1000]; 
     //... 
      func3(arr, ref data); 
     //... 
    return 1; 
} 


private void func3(byte[] arr, ref string data) 
{ 
    char[] a = new char[100]; 
    //... 

    data = new string(a); 
} 

我建议你阅读乔恩斯基特的article about parameter passing了解更多详情。

0

这是因为所有的参数都通过引用传递到方法。 data = new string(a); 使用新引用编写一个字符串的新实例。

var o = new object(); // reference 1 

function void method(object something) 
{ 
    // here we have reference to something in stack, so if we will assign new value to it, we will work with stack copy of a reference. 
    something = null; // we removed reference to something in method not initial o instance 
} 
0

首先,它是一个实例变量,而不是变量。要成为类变量,它必须声明为static

其次,你为什么把它作为一个参数传递给相应的函数呢?你这样做的方式,它会在每个方法中创建一个单独的字符串,并且不会引用原来的字符串。先走一步,直接调用它:

private void func3(byte[] arr) 
{ 
    //... 
    mydata = new string(a); 
} 
0

你按值传递的参考串mydata。这意味着mydata在函数返回后仍然会引用同一个对象,而不管你在函数内部做了什么。如果你想改变字符串mydata,你可以通过引用传递的参考:

public int func1() 
{ 
    //.... 
     func2(/**/, ref mydata); 
    //.... 
    return 1; 
} 

private int func2(/**/, ref string data) 
{ 
    byte[] arr = new byte[1000]; 
     //... 
      func3(arr, ref data); 
     //... 
    return 1; 
} 

private void func3(byte[] arr, ref string data) 
{ 
    char[] a = new char[100]; 
    //... 

    data = new string(a); 
} 
相关问题