// For illustration, not complete source public class List<T> : IEnumerable<T> { private class Enumerator<T> : IEnumerator<T> { // Contains specific implementation of // MoveNext(), Reset(), and Current. public Enumerator(List<T> storage) { // elided } }
public IEnumerator<T> GetEnumerator() { return new Enumerator<T>(this); }
// other List members. }
22 通过定义并实现接口替代继承
基类描述了对象是什么,接口描述了对象将如何表现其行为;
扩展方法可以作用于接口,如System.Linq.Enumerable中有:
1 2 3 4 5 6 7 8 9 10 11 12
public static class Extensions { public static void ForAll<T>( this IEnumerable<T> sequence, Action<T> action) { foreach (T item in sequence) action(item); } } // usage foo.ForAll((n) => Console.WriteLine(n.ToString()));
public struct URLInfo : IComparable<URLInfo>, IComparable { private string URL; private string description; #region IComparable<URLInfo> Members public int CompareTo(URLInfo other) { return URL.CompareTo(other.URL); } #endregion
#region IComparable Members int IComparable.CompareTo(object obj) { if (obj is URLInfo) { URLInfo other = (URLInfo)obj; return CompareTo(other); } else throw new ArgumentException( "Compared object is not URLInfo"); } #endregion }
public class LoggerEventArgs : EventArgs { public string Message { get; private set; } public int Priority { get; private set; } public LoggerEventArgs(int p, string m) { Priority = p; Message = m; } } public class Logger { static Logger() { theOnly = new Logger(); } private Logger() { } private static Logger theOnly = null; public static Logger Singleton { get { return theOnly; } } // Define the event: public event EventHandler<LoggerEventArgs> Log; // add a message, and log it. public void AddMsg(int priority, string msg) { // This idiom discussed below. EventHandler<LoggerEventArgs> l = Log; if (l != null) l(this, new LoggerEventArgs(priority, msg)); } }
public delegate TResult Func<out TResult>(); public delegate TResult Func<in T, out TResult>(T arg); public delegate TResult Func<in T1, T2, out TResult>(T1 arg1, T2 arg2); public delegate void Action<in T>(T arg); public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2); public delegate void Action<in T1, in T2, T3>(T1 arg1, T2 arg2, T3 arg3);