using System; using System.Collections.Generic; using System.Text;
namespace Example16 { interface IPoint { double X { get; set; } double Y { get; set; } double Z { get; set; } } //结构也可以从接口继承 struct Point: IPoint { private double x, y, z; //结构也可以增加构造函数 public Point(double X, double Y, double Z) { this.x = X; this.y = Y; this.z = Z; } public double X { get { return x; } set { x = value; } } public double Y { get { return x; } set { x = value; } } public double Z { get { return x; } set { x = value; } } } //在此简化了点状Geometry的设计,实际产品中还包含Project(坐标变换)等复杂操作 class PointGeometry { private Point value;
public PointGeometry(double X, double Y, double Z) { value = new Point(X, Y, Z); } public PointGeometry(Point value) { //结构的赋值将分配新的内存 this.value = value; } public double X { get { return value.X; } set { this.value.X = value; } } public double Y { get { return value.Y; } set { this.value.Y = value; } } public double Z { get { return value.Z; } set { this.value.Z = value; } } public static PointGeometry operator +(PointGeometry Left, PointGeometry Rigth) { return new PointGeometry(Left.X + Rigth.X, Left.Y + Rigth.Y, Left.Z + Rigth.Z); } public override string ToString() { return string.Format("X: {0}, Y: {1}, Z: {2}", value.X, value.Y, value.Z); } } class Program { static void Main(string[] args) { Point tmpPoint = new Point(1, 2, 3);
PointGeometry tmpPG1 = new PointGeometry(tmpPoint); PointGeometry tmpPG2 = new PointGeometry(tmpPoint); tmpPG2.X = 4; tmpPG2.Y = 5; tmpPG2.Z = 6;
using System; using System.Collections.Generic; using System.Text;
namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01 { class Class1 { public override string ToString() { return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01's Class1"; } } } Class2.cs:
using System; using System.Collections.Generic; using System.Text;
namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02 { class Class1 { public override string ToString() { return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02's Class1"; } } } 主单元(Program.cs):
using System; using System.Collections.Generic; using System.Text;
//使用别名指示符解决同名类型的冲突 //在所有命名空间最外层定义,作用域为整个单元文件 using Lib01Class1 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1; using Lib02Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02.Class1;
class Class1 { //Lib01Class1和Lib02Class2在这可以正常使用 Lib01Class1 tmpObj1 = new Lib01Class1(); Lib02Class2 tmpObj2 = new Lib02Class2(); //TestClass1在这可以正常使用 Test1Class1 tmpObj3 = new Test1Class1(); } } namespace Test2 { using Test1Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1;
class Program { static void Main(string[] args) { //Lib01Class1和Lib02Class2在这可以正常使用 Lib01Class1 tmpObj1 = new Lib01Class1(); Lib02Class2 tmpObj2 = new Lib02Class2();
//注意这里,TestClass1在这不可以正常使用。 //因为,在Test2命名空间内不能使用Test1命名空间定义的别名 //Test1Class1 tmpObj3 = new Test1Class1();
//TestClass2在这可以正常使用 Test1Class2 tmpObj3 = new Test1Class2();