C# 70-536 – Chapter 1
實質型別:
通用參考型別
條件約束:Constrains
/// <summary>
/// CompGen
/// </summary>
/// <typeparam name="T"></typeparam>
class CompGen<T>
where T :IComparable //使用條件約束,讓T只能使用有實作IComparable的型別
{
public T _t1;
public T _t2;
public CompGen(T t1, T t2)
{
_t1 = t1;
_t2 = t2;
}
public T Max()
{
if (_t2.CompareTo(_t1) < 0)
return _t1;
else
return _t2;
}
}
事件:Eventhandler & EventArgs
// Define a class to hold custom event info
public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
message = s;
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
}
// Class that publishes an event
class Publisher
{
// Declare the event using EventHandler<T>
public event EventHandler<CustomEventArgs> RaiseCustomEvent;
public void DoSomething()
{
OnRaiseCustomEvent(new CustomEventArgs("Did something"));
}
protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
{
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
if (handler != null)
{
// Format the string to send inside the CustomEventArgs parameter
e.Message += String.Format(" at {0}", DateTime.Now.ToString());
// Use the () operator to raise the event.
handler(this, e);
}
}
}
Boxing & Unboxing
避免不必要的Boxing,以減少系統負擔。
1.儘可能使用泛型來取代接受Object
2.在定義結構時,覆寫ToString, Equals, GetHash.
型別轉換
1.實做SystemIconvertible時,不能用的方法擲出InvalidCastException
Dotblogs 的標籤:C#