今天,又一次拿起C#高级编程教材。记得刚开始接触Asp.net的时候,我是什么都看不懂的,说真的我挺感谢带我进入asp.net的那位朋友,他告诉我,其实你不需要知道为什么,刚开始就跟着做就好了,也不用刻意去学C#语言的,现在听起来也许觉得不对,但刚开始要不是这样也许我就走不下来了。因为在此之前,我仅会一点C语言。
这让我想起玩游戏,比如说魔兽,刚开始我们是不会去考虑伤害和兵种的,只要能赢就行,但熟悉了以后,就不但想赢,还要赢得漂亮。
好了,下面来写一些值得自己多注意的地方吧。
都知道C#里面有值和引用类型,它们的区别在于存在于堆栈还是堆中,最好的例子还是类和结构的区别。
下面来看这段代码:
using System;
class RefTest
{
public int Width;
public int Height;
}
struct ValTest
{
public int Width;
public int Height;
}
class Test
{
public static void Main()
{
RefTest ref = new RefTest();
ref.Width = 10;
ref.Height = 20;
RefTest ref2 = ref;
Console.WriteLine("ref2 = " + ref2.Width + "x" + ref2.Height );
ref.Width = 20;
ref.Height = 30;
Console.WriteLine("ref2 = " + ref2.Width + "x" + ref2.Height );
ValTest val = new ValTest();
val.Width = 10;
val.Height = 20;
ValTest val2 = val;
Console.WriteLine("val2 = " + val2.Width + "x" + val2.Height );
val.Width = 20;
val.Height = 30;
Console.WriteLine("val2 = " + val2.Width + "x" + val2.Height );
}
}
编译后很容易知道结果,值类型的是不会变的,而引用的将改变,也就是说定义类的会改变,结构的不会改变,我刚开始理解起来挺不容易的,但再回头就容易多了,其实再陌生的东西接触多了也会变得熟悉。
但同样有例外的,比说string就是引用类型,但是下面这段代码大家觉得会是什么呢?
using System;
class Test
{
public static void Main()
{
string s1 = "a string";
string s2 = s1;
Console.WriteLine("s2 = " + s2);
s1 = "another string";
Console.WriteLine("s2 = " + s2);
}
}
第二次输出的会是什么呢?很遗憾,虽然是引用类型,但是在这里它输出的还是 a string。
再接下来是ref 和out 关键字。
using System;
class Test
{
static void someFunction(ints[] Ints, int i)
{
Ints[0] = 100;
i = 100;
}
public static void Main()
{
int i = 0;
int[] Ints = {0,1,2,3,4};
Console.WriteLine("i = " + i);
Console.WriteLine("Ints[0] = " + Ints[0]);
someFunction(Ints, i)
Console.WriteLine("i = " + i);
Console.WriteLine("Ints[0] = " + Ints[0]);
}
}
数组是引用类型,而i是值类型,结果很容易想到,但是如果给i加上ref关键字以后呢?
using System;
class Test
{
static void someFunction(ints[] Ints, ref int i)
{
Ints[0] = 100;
i = 100;
}
public static void Main()
{
int i = 0;
int[] Ints = {0,1,2,3,4};
Console.WriteLine("i = " + i);
Console.WriteLine("Ints[0] = " + Ints[0]);
someFunction(Ints, ref i)
Console.WriteLine("i = " + i);
Console.WriteLine("Ints[0] = " + Ints[0]);
}
}
这里我告诉大家结果,i的值会变成100。因为用了ref关键字,所以对变量做的任何改变都会影响原来对象的值。
out关键字是
using System;
class Test
{
static void someFunction(out int i)
{
i = 100;
}
public static void Main()
{
int i ;//注意,这里对i没有初始化,也不能初始化,否则会报错。
someFunction(out i)
Console.WriteLine("i = " + i);
}
}
好了,今天先写到这里!
转载于:https://www.cnblogs.com/shahouhou/archive/2007/06/20/790903.html