【轉】編寫高品質代碼改善C#程式的157個建議——建議45:為泛型型別參數指定逆變

來源:互聯網
上載者:User

標籤:基類   帶來   man   compareto   rabl   style   情境   pareto   介面   

 

建議45:為泛型型別參數指定逆變

逆變是指方法的參數可以是委託或者泛型介面的參數類型的基類。FCL4.0中支援逆變的常用委託有:

Func<int T,out TResult>

Predicate<in T>

常用委託有:

IComparer<in T>

下面例子示範了泛型型別參數指定逆變所帶來的好處:

    class Program    {        static void Main()        {            Programmer p = new Programmer { Name = "Mike" };            Manager m = new Manager { Name = "Steve" };            Test(p, m);        }        static void Test<T>(IMyComparable<T> t1, T t2)        {            //省略        }    }    public interface IMyComparable<in T>    {        int Compare(T other);    }    public class Employee : IMyComparable<Employee>    {        public string Name { get; set; }        public int Compare(Employee other)        {            return Name.CompareTo(other.Name);        }    }    public class Programmer : Employee, IMyComparable<Programmer>    {        public int Compare(Programmer other)        {            return Name.CompareTo(other.Name);        }    }    public class Manager : Employee    {    }

上面的例子中,如果不為介面IMyComparable的泛型參數T指定in關鍵字,將會導致Test(p,m)編譯錯誤。由於引入了介面的逆變性,這讓方法Test支援了更多的情境。在FCL4.0之後的版本的實際編碼中應該始終注意這一點。

 

 

轉自:《編寫高品質代碼改善C#程式的157個建議》陸敏技

【轉】編寫高品質代碼改善C#程式的157個建議——建議45:為泛型型別參數指定逆變

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.