在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};
在C#中创建类型的更多相关文章
- C++中结构体与类的区别(结构不能被继承,默认是public,在堆栈中创建,是值类型,而类是引用类型)good
结构是一种用关键字struct声明的自定义数据类型.与类相似,也可以包含构造函数,常数,字段,方法,属性,索引器,运算符和嵌套类型等,不过,结构是值类型. 1.结构的构造函数和类的构造函数不同. a. ...
- 关于Emit中动态类型TypeBuilder创建类标记的一点思考
利用TypeBuilder是可以动态创建一个类型,现在有个需求,动态生成一个dll,创建类型EmployeeEx,需要继承原dll里面的Employee类,并包含Employee类上的所有类标记. ...
- 【转载】 Java中String类型的两种创建方式
本文转载自 https://www.cnblogs.com/fguozhu/articles/2661055.html Java中String是一个特殊的包装类数据有两种创建形式: String s ...
- Java归去来第4集:java实战之Eclipse中创建Maven类型的SSM项目
一.前言 如果还不了解剧情,请返回第3集的剧情 Java归去来第3集:Eclipse中给动态模块升级 二.在Eclipse中创建Maven类型的SSM项目 2.1:SSM简介 SSM ...
- 在 QML 中创建 C++ 导入类型的实例
在 QML 中创建 C++ 导入类型的实例 文件列表: Project1.pro QT += quick CONFIG += c++ CONFIG += declarative_debug CONFI ...
- 受检查异常要求try catch,new对象时,就会在堆中创建内存空间,创建的空间包括各个成员变量类型所占用的内存空间
,new对象时,就会在堆中创建内存空间,创建的空间包括各个成员变量类型所占用的内存空间
- 图像处理中创建CDib类时无法选择基类类型时怎么办
图像处理中创建CDib类时无法选择基类类型时怎么办? 类的类型选择Generic Class 在下面的篮筐里输入CObject就行了
- In-Memory:在内存中创建临时表和表变量
在Disk-Base数据库中,由于临时表和表变量的数据存储在tempdb中,如果系统频繁地创建和更新临时表和表变量,大量的IO操作集中在tempdb中,tempdb很可能成为系统性能的瓶颈.在SQL ...
- 详解Linux交互式shell脚本中创建对话框实例教程_linux服务器
本教程我们通过实现来讲讲Linux交互式shell脚本中创建各种各样对话框,对话框在Linux中可以友好的提示操作者,感兴趣的朋友可以参考学习一下. 当你在终端环境下安装新的软件时,你可以经常看到信息 ...
随机推荐
- 【恒天云】OpenStack和CloudStack对比研究报告
摘自恒天云:http://www.hengtianyun.com/download-show-id-8.html 1. 概述 常见的IaaS开源平台有OpenStack.CloudStack.Euca ...
- Django中的Model(字段)
Model Django中的model是用来操作数据库的,Model是一个ORM框架,我们只需要关心model的操作,而不需要关心到底是哪一种数据库. 一.基本知识: 数据库引擎: Django中自带 ...
- 自定义实现MPVolumeView音量控件
http://blog.csdn.net/theonezh/article/details/8158420 http://www.cnblogs.com/cate/ios/ http://www.cn ...
- Stage3D学习笔记(四):正交矩阵
我们上一章节显示图片的时候,会发现我们制定的顶点在Stage3D中其实是存在一个区间的: x轴(从左到右):[-1.0-1.0] y轴(从下到上):[-1.0-1.0] z轴(从近到远):[0-1.0 ...
- sudo: /etc/sudoers is mode 0640, should be 0440解决办法
ubuntu或者CentOS中,/etc/sudoer 的权限为 0440时才能正常使用,否则sudo命令就不能正常使用.出现类似:sudo: /etc/sudoers is mode 0640, s ...
- hdu 5443 The Water Problem 线段树
The Water Problem Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php? ...
- ios开发——实战OC篇&SQLite3的实际应用
SQLite3的实际应用 前面的文章中介绍了SQlite,并且介绍了他的各种语法及使用方法. 但是没有正在项目中使用特,今天就开始做一个小小的实例,就是使用SQLite3来实现数据库的相应操作并且把他 ...
- iOS开发——UI篇OC篇&UITableView多项选择
UITableView多项选择 自定义cell和取到相应的cell就行了 TableViewCell.h #import <UIKit/UIKit.h> @interface TableV ...
- BAPI_ACC_DOCUMENT_POST Enter rate / GBP rate type M for Error SG105
Folks, I was wondering if I could get a bit of help here as I've been racking my brains on it for ag ...
- 进程关系之tcgetpgrp、tcsetpgrp和tcgetsid函数
需要有一种方法来通知内核哪一个进程组是前台进程组,这样,终端设备驱动程序就能了解将终端输入和终端产生的信号送到何处. #include <unistd.h> pid_t tcgetpgrp ...