日期:2014-05-18 浏览次数:20869 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("演示值类型引用:"); ValueTypeWarpper<int> i = 3; ValueTypeWarpper<int> j = 3; ValueTypeWarpper<int> refi = i; Console.WriteLine("i = {0}, j = {1}.", i, j); Console.WriteLine("i == j? {0}", i == j); refi.Value = 7; Console.WriteLine("i = {0}, j = {1}.", i, j); Console.WriteLine("i == j? {0}", i == j); Console.WriteLine("i > j? {0}", i > j); Console.WriteLine("演示值类型作为协变:"); object[] x = new ValueTypeWarpper<int>[] { 0, 1, 2, 3, 4, 5, 6 } .Where(y => y % 2 == 0).ToArray(); Console.WriteLine(string.Join(", ", x)); } } class ValueTypeWarpper<T> { public static implicit operator T(ValueTypeWarpper<T> x) { return x.Value; } public static implicit operator ValueTypeWarpper<T>(T x) { return new ValueTypeWarpper<T>() { Value = x }; } public T Value { get; set; } public override string ToString() { return Value.ToString(); } public override bool Equals(object obj) { return obj != null && obj.GetType() == this.GetType() && Value.Equals((obj as ValueTypeWarpper<T>).Value); } public static bool operator ==(ValueTypeWarpper<T> v1, ValueTypeWarpper<T> v2) { return v1.Equals(v2); } public static bool operator !=(ValueTypeWarpper<T> v1, ValueTypeWarpper<T> v2) { return !v1.Equals(v2); } public override int GetHashCode() { return Value.GetHashCode(); } } }