创建构造器的一个例子:
class Circle { private int radius; public Circle() //默认构造器 { radius = 0; } public Circle(int initalRadius) //重载的构造器 { radius = initialRadius; } public double Area() { return Math.PI * radius * radius; } }
使用多文件时的写法:
Circ1.cs内容:
partial class Circle { public Circle() //默认构造器 { radius = 0; } public Circle(int initalRadius) //重载的构造器 { radius = initialRadius; } }Circ2.cs内容:
partial class Circle { private int radius; public double Area() { return Math.PI * radius * radius; } }
调用自己的字段时,使用this关键字:
class Point { private int x, y; private static int objectCount = 0; public Point() { this.x = -1; this.y = -1; objectCount++; } public Point(int x, int y) { this.x = x; this.y = y; objectCount++; } public double DistanceTo(Point other) { int xDiff = this.x - other.x; //注意此处 int yDiff = this.y - other.y; double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff)); return distance; } public static int ObjectCount() => objectCount; //ObjectCount方法返回objectCount的值 }
=======
静态方法/数据使用static标记
只能访问标记为static的其他方法和字段
静态类(不允许被new:
class Math { ... public const double PI = 3.14159265358979; }
匿名类:
var myxxxx = new {Name = "xx", Age = 123}; Console.WriteLine($"Name:{myxxxx.Name},Age:{myxxxx.Age}"); var myyyyy = new {Name = "yy", Age = 321}; myxxxx = myyyyy; //合法,因为具有相同类型
转载保留版权:晨旭的博客 » 《创建和管理类和对象 – 第七章 – C# 从入门到放弃》如果喜欢可以: 点击右侧上方的邮件订阅,订阅本站