c# class

2019-09-30  本文已影响0人  柒轩轩轩轩

field

是class的成员,是一个成员

readonly修饰符

字段初始化

overload

类型里的方法可以进行重载(允许多个同名的方法同时存在),只要这些方法的签名不同就行

void Foo (int x) {}
void Foo(double x) {}
void Foo(int x, double y) {}

构造函数

public class Panda
{
  string name;
  public Panda(string n) => name = n;
}

构造函数的重载

public class Wine 
{
    public decimal Price;
    public int Year;

    public Wine(decimal price)
  {
    Price = price;
  }
  public Wine(decimal price, int year) : this(price)
  {
    Year = year;
  }
}

public Wine (decimal price, DateTime date): this(price, Wine.GetYear()) 
{
  Date = date
}
public static int GetYear(){return 1998;}

构造函数和字段的初始化顺序

非pulic的构造函数

class Test 
{
  public static void Main(string[] args)
  {
    var wine = Wine.CreateInstance();
  }
}

public class Wine
{
  Wine(){}
  public static Wine CreateInstance(){
  return new Wine();
}

}

Deconstructor

class Rectangle 
{
  public readonly float Width, Height;
  public Rectangle(float width, float height){
    Width = width;
    Height = height;
  }
  public void Deconstruct(out float width, out float height){
    width = Width;
    height = Height;
  }  
}

class Test 
{
  public static void Main(string[] args){
  var rect = new Rectangle(3,4);
  //rect.Deconstruct(out var width, out var height);
  var (width, height) = rect;
  Console.WriteLine(width + " " + height); //3,4
  }
}
public static class Extension
{
  public static void Deconstruct(this Rectangle rect, out float width, out float height)
  {
     width = rect.Width;
     height = rect.Height;
  }
}

...
var rect = new Rectangle(3,4);
Extensions.Deconstruct(rect, out var width, out var height);
...

对象初始化器

public class Bunny
{
  public string Name;
  public bool LikesCarrots;
  public bool LikesHumans;

  public Bunny () {}
  public Bunny(string n) {Name = n;}
}

...
Bunny b1 = new Bunny{ Name ="Bo, LikesCarrots = true, LikesHumans = false};
Bunny b2 = new Bunny("Bo") { LikesCarrots = true,  LikesHumans = false}

如果不适用初始化器,上例中的构造函数也可以使用可选参数

public Buuny(string name, bool likesCarrots = false, bool likesHumans = false)
{
  Name = name;
  LikesCarrots = likesCarrots;
  LikesHumans = likesHumans
}

可选参数方式

This 引用

public class Panda
{
  public Panda Mate;
  public void Marry (Panda partner)
  {
  Mate = partner;
  partner.Mate = this;
  }
}

属性 Property

public class Stock
{
  decimal currentPrice;
  public decimal CurrentPrice
  {
    get { return currentPrice;}
    set { currentPrice = value;}
  }
}

属性的get set

只读和计算的属性

自动属性

public class Stock
{
  ...
  public decimal CurrentPrice { get; set; }
}
public decimal CurrentPrice {get; set;} =123;
public int Maxinum {get;} = 999;
public class Foo 
{
  private decimal x;
  public decimal x {
    get { return x;}
    private set {x = Math.Round(value, 2)}
  }
上一篇 下一篇

猜你喜欢

热点阅读