Feeds:
文章
留言

Archive for 六月 11th, 2006

Read Full Post »

如下範例,為自己的型別提供轉換,可以使用如下紅色字樣的關鍵子來宣告,黃色 mark 區域是轉換後的型別,參數是自訂型別。
 
    public class T {
        // T => int 隱性型別轉換
        public static implicit operator int(T t) {
            return 100;
        }
 
        // int => T 隱性型別轉換
        public static implicit operator T(int i) {
            return new T();
        }
 
        // T => float 顯性型別轉換
        public static explicit operator float(T t) {
            return 9.9f;
        }
 
        // float => T 顯性型別轉換
        public static explicit operator T(float f) {
            return new T();
        }
        public override string ToString() {
            return "T Class";
        }
    }
 
 class Program {
        static void Main(string[] args) {
            T t = new T();
            int i = t;
            Console.WriteLine(i); // 100, static implicit operator int 
 
            float f = (float)t;
            Console.WriteLine(f); // 9.9, static explicit operator float
 
            f = t;
            Console.WriteLine(f); // 100, static implicit operator int
            t = (T)3.1f;
            Console.WriteLine(t.ToString() ); // T class
 
            t = 100;
            Console.WriteLine(t.ToString()); // T class
        }
}

Read Full Post »