C#参数值传递与引用传递问题,太久没有关注这些基础的C#知识,导致很多东西都忘了,幸好有公司小培训帮助补充了这些。
本次例子以传递类对象参数,对类对象的属性值进行写操作。(接着昨天写序列化的代码来写的)
class Program
{
public static void Main(string[] args)
{
TestRefObject1();
Console.Read();
}
public static void TestRefObject1()
{
TestSerializationObject obj1 = new TestSerializationObject();
obj1.Attr3 = 0;
AddAttr3_1(obj1);
Console.WriteLine("1:"+obj1.Attr3);
TestSerializationObject obj2 = new TestSerializationObject();
obj2.Attr3 = 0;
AddAttr3_2(ref obj2);
Console.WriteLine("2:" + obj2.Attr3);
TestSerializationObject obj3 = new TestSerializationObject();
obj3.Attr3 = 0;
AddAttr3_3(obj3);
Console.WriteLine("3:" + obj3.Attr3);
TestSerializationObject obj4 = new TestSerializationObject();
obj4.Attr3 = 0;
AddAttr3_4(ref obj4);
Console.WriteLine("4:" + obj4.Attr3);
string str1 = "nihao,";
ChangeStr(str1);
Console.WriteLine(str1);
string str2 = "nihao,";
ChangeStr(ref str2);
Console.WriteLine(str2);
int a1 = 0;
ChangeInt(a1);
Console.WriteLine(a1);
int a2 = 0;
ChangeInt(ref a2);
Console.WriteLine(a2);
}
public static void ChangeInt(int a)
{
a++;
}
public static void ChangeInt(ref int a)
{
a++;
}
public static void ChangeStr(string str)
{
str = str + "haha";
}
public static void ChangeStr(ref string str)
{
str = str + "haha";
}
public static void AddAttr3_1(TestSerializationObject obj)
{
obj.Attr3++;
}
public static void AddAttr3_2(ref TestSerializationObject obj)
{
obj.Attr3++;
}
public static void AddAttr3_3(TestSerializationObject obj)
{
obj=new TestSerializationObject();
obj.Attr3 = 5;
obj.Attr3++;
}
public static void AddAttr3_4(ref TestSerializationObject obj)
{
obj = new TestSerializationObject();
obj.Attr3 = 5;
obj.Attr3++;
}
}
public class TestSerializationObject
{
public string Attr1
{
get;
set;
}
public string Attr2
{
get;
set;
}
public int Attr3
{
get;
set;
}
}
先想想上面的代码的答案是什么?
想
想
想
想
想
想
想
想
恩,答案是
这里说明:由于类对象属于引用类型,在进行参数传递时,会传入栈中对象的地址。
对于引用类型:
1、在修改变量本身时,结果类似于值传递,即不会改变传递前的变量的值(本例中的string)
2、在修改变量的属性或字段时,才是引用传递,会影响到传递前的变量的值(本例中的类)
3、参数使用了ref后,才是真正的引用传递,不管修改变量本身还是修改变量的属性或字段,都会影响到传递前的变量的值
而值传递,只是传递了对象的值拷贝。
注意将例子中的TestSerializationObject类改为Struct,会出现什么情况呢?
注意struct类型为值类型。
结果显示为:
这样子就对上了!
附上C#方法、类等默认访问修饰符,这个博客介绍的比较全:
http://blog.csdn.net/andrew_wx/article/details/6843426
想
想
想
想