在C#中创建类型

简介: 重载构造函数: using System;public class Wine{ public decimal Price; public int Year; public Wine (decimal price) { Pric...

重载构造函数:

using System;

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 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 };

this引用:

public class Panda
{
  public Panda Mate;

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

属性:

public class Stock
{
  decimal currentPrice;           // The private "backing" field

  public decimal CurrentPrice     // The public property
  {
     get { return currentPrice; } set { currentPrice = value; }
  }
}

只读和已计算属性:

public class Stock
{
  string  symbol;
  decimal purchasePrice, currentPrice;
  long    sharesOwned;

  public Stock (string symbol, decimal purchasePrice, long sharesOwned)
  {
    this.symbol = symbol;
    this.purchasePrice = currentPrice = purchasePrice;
    this.sharesOwned = sharesOwned;
  }

  public decimal CurrentPrice  { get { return currentPrice;             }
                                 set { currentPrice = value;            } }
  public string Symbol         { get { return symbol;                   } }
  public decimal PurchasePrice { get { return purchasePrice;            } }
  public long    SharesOwned   { get { return sharesOwned;              } }
  public decimal Worth         { get { return CurrentPrice*SharesOwned; } }
}

class Test
{
  static void Main()
  {
    Stock msft = new Stock ("MSFT", 20, 1000);
    Console.WriteLine (msft.Worth);                // 20000
    msft.CurrentPrice = 30;
    Console.WriteLine (msft.Worth);                // 30000
  }
}

自动属性:

public class Stock
{
  // ...
  public decimal CurrentPrice { get; set; }
}

get 和 set 访问:

public class Foo
{
  private decimal x;
  public decimal X
  {
    get          {return x;} 
    internal set {x = value;}
  }
}

实现索引:

public class Portfolio
{
  Stock[] stocks;
  public Portfolio (int numberOfStocks)
  {
    stocks = new Stock [numberOfStocks];
  }

  public int NumberOfStocks { get { return stocks.Length; } }

  public Stock this [int index]      // indexer
  { 
    get { return stocks [index];  }
    set { stocks [index] = value; }
  }
}

class Test
{
  static void Main()
  {
    Portfolio portfolio = new Portfolio(3);
    portfolio [0] = new Stock ("MSFT", 20, 1000);
    portfolio [1] = new Stock ("GOOG", 300, 100);
    portfolio [2] = new Stock ("EBAY", 33, 77);

    for (int i = 0; i < portfolio.NumberOfStocks; i++)
      Console.WriteLine (portfolio[i].Symbol);
  }
}

多索引:

public class Portfolio
{
  ...
  public Stock this[string symbol]
  {
    get
    {
      foreach (Stock s in stocks)
        if (s.Symbol == symbol)
          return s;
      return null;
    }
  }
}

静态构造函数:

class Test
{
  static Test()
  {
    Console.WriteLine ("Type Initialized");
  }
}

Partial方法:

// PaymentFormGen.cs — auto-generated
partial class PaymentForm
{
  // ...
  partial void ValidatePayment(decimal amount);
}
// PaymentForm.cs — hand-authored
partial class PaymentForm
{
  // ...
  // partial void ValidatePayment(decimal amount)
  {
    if (amount > 100)
    {
      // ...
    }
  }
}

继承:

public class Asset
{
  public string  Name;
  public decimal PurchasePrice, CurrentPrice;
}
public class Stock : Asset   // inherits from Asset
{
  public long SharesOwned;
}

public class House : Asset   // inherits from Asset
{
  public decimal Mortgage;
}

class Test
{
  static void Main()
  {
    Stock msft = new Stock()
    { Name="MSFT", PurchasePrice=20, CurrentPrice=30, SharesOwned=1000 };

    House mansion = new House
    { Name="McMansion", PurchasePrice=300000, CurrentPrice=200000,
      Mortgage=250000 };

    Console.WriteLine (msft.Name);           // MSFT
    Console.WriteLine (mansion.Name);        // McMansion

    Console.WriteLine (msft.SharesOwned);    // 1000
    Console.WriteLine (mansion.Mortgage);    // 250000
  }
}

多态:

class Test
{
  static void Main()
  {
    Stock msft    = new Stock ... ;
    House mansion = new House ... ;
    Display (msft);
    Display (mansion);
  }

  public static void Display (Asset asset)
  {
    System.Console.WriteLine (asset.Name);
  }
}
static void Main() { Display (new Asset()); }    // Compile-time error

public static void Display (House house)         // Will not accept Asset
{
  System.Console.WriteLine (house.Mortgage);
}

向下转换:

Stock msft = new Stock();
Asset a = msft;                      // upcast
Stock s = (Stock)a;                  // downcast
Console.WriteLine (s.SharesOwned);   // <No error>
Console.WriteLine (s == a);          // true
Console.WriteLine (s == msft);       // true

虚拟函数成员:

public class Asset
{
  ...
  public virtual decimal Liability { get { return 0; } }
}
public class Stock : Asset { ... }

public class House : Asset
{
  ...
  public override decimal Liability { get { return Mortgage; } }
}
House mansion = new House
 { Name="McMansion", PurchasePrice=300000, CurrentPrice=200000,
   Mortgage=250000 };

Asset a = mansion;
decimal d2 = mansion.Liability;      // 250000

抽象类和抽象成员:

public abstract class Asset
{
  ...
  public abstract decimal NetValue { get; }   // Note empty implementation
}

public class Stock : Asset
{
  ...                                     // Override an abstract method
  public override decimal NetValue        // just like a virtual method.
  {
    get { return CurrentPrice * SharesOwned; }
  }
}

public class House : Asset     // Every non abstract subtype must
{                              // define NetValue.
  ...
  public override decimal NetValue
  {
    get { return CurrentPrice - Mortgage; }
  }
}

new 和 virtual

public class BaseClass
{
  public virtual void Foo()  { Console.WriteLine ("BaseClass.Foo"); }
}

public class Overrider : BaseClass
{
  public override void Foo() { Console.WriteLine ("Overrider.Foo"); }
}

public class Hider : BaseClass
{
  public new void Foo()      { Console.WriteLine ("Hider.Foo"); }
}
Overrider o = new Overrider();
BaseClass b1 = o;
o.Foo();                           // Overrider.Foo
b1.Foo();                          // Overrider.Foo

Hider h = new Hider();
BaseClass b2 = h;
h.Foo();                           // Hider.Foo
b2.Foo();                          // BaseClass.Foo

GetType() 和 typeof

using System;

public class Point {public int X, Y;}

class Test
{
  static void Main()
  {
    Point p = new Point();
    Console.WriteLine (p.GetType().Name);             // Point
    Console.WriteLine (typeof (Point).Name);          // Point
    Console.WriteLine (p.GetType() == typeof(Point)); // True
    Console.WriteLine (p.X.GetType().Name);           // Int32
    Console.WriteLine (p.Y.GetType().FullName);       // System.Int32
  }
}

显式接口实现:

interface I1 { void Foo(); }
interface I2 { int Foo(); }

public class Widget : I1, I2
{
  public void Foo ()
  {
    Console.WriteLine ("Widget's implementation of I1.Foo");
  }

  int I2.Foo ()
  {
    Console.WriteLine ("Widget's implementation of I2.Foo");
    return 42;
  }
}
Widget w = new Widget();
w.Foo();                      // Widget's implementation of I1.Foo
((I1)w).Foo();                // Widget's implementation of I1.Foo 
((I2)w).Foo();                // Widget's implementation of I2.Foo

虚拟地实现接口成员:

public interface IUndoable { void Undo(); }

public class TextBox : IUndoable
{
  public virtual void Undo()
  {
     Console.WriteLine ("TextBox.Undo");
  }
}

public class RichTextBox : TextBox
{
  public override void Undo()
  {
    Console.WriteLine ("RichTextBox.Undo");
  }
}
RichTextBox r = new RichTextBox();
r.Undo();                          // RichTextBox.Undo
((IUndoable)r).Undo();             // RichTextBox.Undo
((TextBox)r).Undo();               // RichTextBox.Undo

在子类中重新实现一个接口:

public interface IUndoable { void Undo(); }

public class TextBox : IUndoable
{
  void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); }
}

public class RichTextBox : TextBox, IUndoable
{
  public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}
RichTextBox r = new RichTextBox();
r.Undo();                 // RichTextBox.Undo      Case 1
((IUndoable)r).Undo();    // RichTextBox.Undo      Case 2
public class TextBox : IUndoable
{
  public void Undo() { Console.WriteLine ("TextBox.Undo"); }
}
RichTextBox r = new RichTextBox();
r.Undo();                 // RichTextBox.Undo      Case 1
((IUndoable)r).Undo();    // RichTextBox.Undo      Case 2
((TextBox)r).Undo();      // TextBox.Undo          Case 3

替代接口重新实现:

public class TextBox : IUndoable
{
  void IUndoable.Undo()         { Undo(); }   // Calls method below
  protected virtual void Undo() { Console.WriteLine ("TextBox.Undo"); }
}

public class RichTextBox : TextBox
{
  protected override void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}

Flags enums枚举:

[Flags]
public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }
BorderSides leftRight = BorderSides.Left | BorderSides.Right;

if ((leftRight & BorderSides.Left) != 0)
   System.Console.WriteLine ("Includes Left");   // Includes Left

string formatted = leftRight.ToString();   // "Left, Right"

BorderSides s = BorderSides.Left;
s |= BorderSides.Right;
Console.WriteLine (s == leftRight);   // True

s ^= BorderSides.Right;               // Toggles BorderSides.Right
Console.WriteLine (s);                // Left  

Enum枚举类型安全问题:

static bool IsFlagDefined (Enum e)
{
  decimal d;
  return ! decimal.TryParse(e.ToString(), out d);
}

[Flags]
public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }

static void Main()
{
  for (int i = 0; i <= 16; i++)
  {
    BorderSides side = (BorderSides)i;
    Console.WriteLine (IsFlagDefined (side) + " " + side);
  }
}

泛型:

public class Stack<T>
{
  int position;
  T[] data = new T[100];
  public void Push (T obj)        { data[position++] = obj;  }
  public T Pop ()                 { return data[--position]; }
}
Stack<int> stack = new Stack<int>(); 
stack.Push(5);
stack.Push(10);
int x = stack.Pop();

泛方法:

static void Swap<T> (ref T a, ref T b)
{
  T temp = b;
  a = b;
  b = temp;
}

默认泛值:

static void Zap<T> (T[] array)
{
  for (int i = 0; i < array.Length; i++)
    array[i] = default(T);
}

约束:

static T Max <T> (T a, T b) where T : IComparable<T>
{
  return a.CompareTo (b) > 0 ? a : b;
}
static void Initialize<T> (T[] array) where T : new()
{
  for (int i = 0; i < array.Length; i++)
    array[i] = new T(); 
}
class Stack<T>
{
  Stack<U> FilteredStack<U>() where U : T {...}
}

泛型和协方差:

class Animal {}
class Bear : Animal {}
public class ZooCleaner
{
  public static void Wash<T> (Stack<T> animals) where T : Animal {}
}
Stack<Bear> bears = new Stack<Bear>();
ZooCleaner.Wash (bears);

自引用泛型声明:

interface IEquatable<T> { bool Equals (T obj); }

public class Balloon : IEquatable<Balloon>
{
  string color;
  int cc;

  public bool Equals (Balloon b)
  {
    if (b == null) return false;
    return b.color == color && b.cc == cc;
  }
}

泛型类型中的静态数据唯一:

public class Bob<T> { public static int Count; }

class Test
{
  static void Main()
  {
    Console.WriteLine (++Bob<int>.Count);     // 1
    Console.WriteLine (++Bob<int>.Count);     // 2
    Console.WriteLine (++Bob<string>.Count);  // 1
    Console.WriteLine (++Bob<object>.Count);  // 1
  }
}

对象初始化:

List<int> list = new List<int> {1, 2, 3};
目录
打赏
0
0
0
0
20
分享
相关文章
【Azure Function】C#独立工作模式下参数类型 ServiceBusReceivedMessage 无法正常工作
Cannot convert input parameter 'message' to type 'Azure.Messaging.ServiceBus.ServiceBusReceivedMessage' from type 'System.String'.
118 73
|
4月前
|
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
38 0
|
4月前
|
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
108 1
|
4月前
|
c# - 运算符<<不能应用于long和long类型的操作数
在C#中,左移运算符的第二个操作数必须是 `int`类型,因此需要将 `long`类型的位移计数显式转换为 `int`类型。这种转换需要注意数据丢失和负值处理的问题。通过本文的详细说明和示例代码,相信可以帮助你在实际开发中正确使用左移运算符。
68 3
|
5月前
|
C#
C# 可空类型(Nullable)
C# 单问号 ? 与 双问号 ??
93 12
|
7月前
|
C# 语法基础全解
C# 语言类型全解
50 0
C# 中的记录(record)类型和类(class)类型对比总结
C# 中的记录(record)类型和类(class)类型对比总结
104 0
聊聊 C# dynamic 类型,并分享一个将 dynamic 类型变量转为其它类型的技巧和实例
聊聊 C# dynamic 类型,并分享一个将 dynamic 类型变量转为其它类型的技巧和实例
297 0
|
7月前
|
揭秘C#.Net编程秘宝:结构体类型Struct,让你的数据结构秒变高效战斗机,编程界的新星就是你!
【8月更文挑战第4天】在C#编程中,结构体(`struct`)是一种整合多种数据类型的复合数据类型。与类不同,结构体是值类型,意味着数据被直接复制而非引用。这使其适合表示小型、固定的数据结构如点坐标。结构体默认私有成员且不可变,除非明确指定。通过`struct`关键字定义,可以包含字段、构造函数及方法。例如,定义一个表示二维点的结构体,并实现计算距离原点的方法。使用时如同普通类型,可通过实例化并调用其成员。设计时推荐保持结构体不可变以避免副作用,并注意装箱拆箱可能导致的性能影响。掌握结构体有助于构建高效的应用程序。
210 7
C#.Net筑基-类型系统②常见类型 --record是什么类型?
`record`在C#中是一种创建简单、只读数据结构的方式,常用于轻量级数据传输。它本质上是类(默认)或结构体的快捷形式,包含自动生成的属性、`Equals`、`ToString`、解构赋值等方法。记录类型可以继承其他record或接口,但不继承普通类。支持使用`with`语句创建副本。例如,`public record User(string Name, int Age)`会被编译为包含属性、相等比较和`ToString()`等方法的类。记录类型提供了解构赋值和自定义实现,如密封的`sealed`记录,防止子类重写。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等