using System;
using System.Collections.Generic;
namespace Learn
{
using Learn5;
using Learn6;
class Program
{
static void Main(string[] args)
{
Learn5.Test t5 = new Learn5.Test();
Learn6.Test t6 = new Learn6.Test();
t5.Print("C#5");
t6.Print("C#6");
Learn5.Rectangle r5 = new Learn5.Rectangle();
Learn6.Rectangle r6 = new Learn6.Rectangle();
//t5不为空时调用
if (t5 != null)
{
string r5IsSquare = string.Format("r5是不是正方形:{0}.创建时间是{1}", t5.IsSquare(r5), r5.CreateTime);//C#5
t5.Print(r5IsSquare);
foreach (var p in r5.Point.Keys)
{
t5.Print(string.Format("第{0}个点为({1},{2})",p+1,r5.Point[p][0], r5.Point[p][1]));
}
}
//t6不为空时调用
string r6IsSquare = $"r6是不是正方形:{t6?.IsSquare(r6)}.创建时间是{r6?.CreateTime}";//C#6
t6?.Print(r6IsSquare);
foreach (var p in r6.Point.Keys)
{
t6?.Print($"第{p + 1}个点为({r6.Point[p][0]},{r6.Point[p][1]})");
}
//r5.Id = 5; 只读
//r6.Id = 5; 只读
}
}
}
//C#5
namespace Learn5
{
public class Test
{
public void Print(string context)
{
Console.WriteLine(context);
}
public bool IsSquare(Rectangle rect)
{
if (rect == null) return false;
return rect.Height == rect.Width;
}
}
public class Rectangle
{
//实例化类是属性初始值
public Rectangle()
{
Height = 1;
Width = 1;
}
public double Height { get; set; }
public double Width { get; set; }
//只读属性
private readonly int id = 1;
public int Id
{
get { return id; }
}
//属性
public string CreateTime
{
get { return DateTime.Now.ToString(); }
}
//字典赋值
public Dictionary<int, int[]> Point = new Dictionary<int, int[]>()
{
{ 0,new []{0,0}},
{ 1,new []{0,1}},
{ 2,new []{1,0}},
{ 3,new []{1,1}},
};
}
}
//C#6
namespace Learn6
{
using static System.Console;//引用静态类
public class Test
{
public void Print(string context)
{
WriteLine(context);//这里可以不用加Console
}
public bool IsSquare(Rectangle rect) => rect?.Height == rect?.Width && rect != null;//如果只有一行的话可以使用lambda表达式去写
}
public class Rectangle
{
//属性初始化
public double Height { get; set; } = 1;
public double Width { get; set; } = 1;
//只读属性
public int Id { get; } = 2;
//属性lambda
public string CreateTime => DateTime.Now.ToString();//属性单行一样也可以使用
//字典赋值
public Dictionary<int, int[]> Point = new Dictionary<int, int[]>()
{
[0] = new[] { 0, 0 },
[1] = new[] { 0, 1 },
[2] = new[] { 1, 0 },
[3] = new[] { 1, 1 },
};
}
}
C#_C#6简单使用
最新推荐文章于 2024-02-21 08:30:23 发布