Circle c; c = new Circle(42); Circle refc; refc = c; //c与refc指向同一地址
正确的复制类的方法(包括复制私有数据):
class Circle { private int radius; ... public Circle Clone() { //创建新的Circle对象 Circle clone = new Circle(); //将私有的数据从this复制到clone clone.radius = this.radius; //返回包含克隆数据的新Circle对象 return clone; } }
null值:
Circle c = new Circle(42); Circle copy = null; ... if(copy == null) { copy = c; ... }
对于值类型,需要将变量生命为可空值类型:
int i = null; //非法 int? i = null; //合法
可空类型的属性:
int? i = null; ... if(!i.HasValus) { i = 99; } else { Console.WriteLine(i.Value); }
ref:
static void example(ref int a) { a++; } static void Main() { int arg = 42; example(ref arg); //arg=43 }
out:
static void example(out int a) { a = 42; } static void Main() { int arg; example(out arg); //arg=42 }
object:
Circle c; c = new Circle(42); object o; o = c;
转载保留版权:晨旭的博客 » 《理解值和引用-第八章-C#从入门到放弃》如果喜欢可以: 点击右侧上方的邮件订阅,订阅本站