在C#中创建类型

重载构造函数:

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};
时间: 2024-11-08 16:43:53

在C#中创建类型的相关文章

如何在SharePoint中创建 Lookup 类型的Site Column解决跨站问题

在某些情况下,我们需要去引用其他List中的数据,比如在网站集(Site Collection)上有个List叫Country,在其子网站(WebSite)有个List叫Employee,如果要在子Site上的Employee去引用Country中的数据,一般我们会在Site Collection上创建一个网站栏(Site Column).这是一种解决方案.还有一种解决方案,我们也可以在项目中创建一个Lookup 类型的 Site Column,其Scope为Site,顺着思路,我理所应当的创建

Oracle中创建全文索引支持的类型

Oracle中创建全文索引支持的类型 只能在类型:VARCHAR2, CLOB, BLOB, CHAR, BFILE, XMLType, and URIType上创建: 不能在类型:NCLOB,NVARCHAR2,NCHAR,DATE,NUMBER,TIMESTAMP上创建  

在ASP.NET中创建自定义配置节(翻译)

asp.net|创建|asp.net 一.介绍 ASP.NET Web应用程序用一种内置的方法访问简单的"键/值"配置数据.在Web.config文件中,你可以创建节来存储简单的"键/值"对.例如,新建一个ASP.NET项目,在Web.config文件中添加如下的标记作为元素的子标记: 该节包含了用两个标记定义的"键/值"对,你可以通过Page对象内置的ConfigurationSettings属性获得它们的值.作为开始,在你的项目中新建一个名为

在Eclipse中创建新的重构功能

创建 对重构的强大支持是软件开发人员喜爱Eclipse的一个最为重要的原因.而Eclipse还有一个至少和重构不相上下的优点,那就是其近乎无懈可击的可扩展性.这两者的结合意味着我们可以根据自己的需要来创建展新的重构功能. 介绍 重构在现代软件开发过程中扮演着重要的角色,它能够减轻软件开发人员的工作负担,提高软件开发的生产效率.为了阐明重构的重要性,我们在这里引用了developerWorks上David Carew提供的关于重构的教程中的一段话: 现在,一个开发者的工作大部分在于对现有的代码进行

JSP实战:JBuilder2005中创建数据库表

js|创建|数据|数据库 1.在Oracle的SQL Plus工具中,以具有DBA权限的用户登录数据库. system/manger@to_128 @后的to_128为数据库的连接串名,需要根据具体情况更改,如果数据库是在本地,则可以省略@和连接串. 2.创建jbuser用户,指定密码为abc. SQL> create user jbuser identified by abc; 3.为jbuser用户分配connect和resource角色权限. SQL> grant connect ,re

在VB.Net中创建使用控件数组

创建|控件|数组   在VB.Net中创建使用控件数组 首先创建一个Button类型控件数组: 1.创建"Windows应用程序"类型的工程,添加名为ButtonArray的类,并使该类继承 System.Collection.CollectionBase 类.System.Collections.CollectionBase类是.NET框架类库中为集合操作提供抽象的基类,通过对它的继承可以为我们的ButtonArray类具备集合增加.删除.索引的功能. 2.为ButtonArray类

在Informix中创建并使用函数索引

随着数据量以惊人速度不断增长,数据库管理系统将继续关注性能问题.本文主要介绍一种名为函数索引(functional index)的性能调优技术.根据数据库使用情况的统计信息创建并使用函数索引,可以显著提升SELECT 查询的性能.通过本文了解如何在IBM Informix Dynamic Server 中创建和使用函数索引并最大限度提升查询性能. 简介 在选择数据库管理系统(DBMS)时,性能是一个关键的考虑因素.在执行SELECT.INSERT.UPDATE 和 DELETE 操作时,很多因素

在C++中创建并使用Web服务

Web服务的确是.net中让人激动的部分--但它们本身比.net要大.其中的道理很简单.几乎所有你能叫出名字的服务都有一些执行服务器端代码的机制:你在浏览器的地址栏中输入一个URL:接收到你的请求,服务器上就开始运行什么东西,然后以html页面返回你要的结果.它可能是ASP,ASP.NET,Servlets,甚至是五年前通过CGI触发的Perl本.因此想象一下,如果运行代码返回的是XML格式而非HTML格式的结果,并且服务请求并非是在浏览器地址栏中输入的url,而是某些代码中以HTTP中的GET

如何在Microsoft Visual Studio 2005中创建控制台应用程序

在 Visual Studio 2005 中创建控制台应用程序 在 Visual Studio 2005 中的"文件" 菜单上,指向"新建" 并单击"项目". 在"新建项目" 对话框中,选择一种语言,然后在"项目类型" 框中选择"Windows". 在"模板" 框中,选择"控制台应用程序" . 在"位置" 框中,键入指向应用程序