【轉】編寫高品質代碼改善C#程式的157個建議——建議44:理解委託中的協變

來源:互聯網
上載者:User

標籤:ring   通過   res   return   編寫高品質代碼   過程   isa   理解   manage   

 

建議44:理解委託中的協變

委託中的泛型變數天然是部分支援協變的。為什麼是“部分支援協變”?看下面樣本:

   class Program    {        public delegate T GetEmployeeHanlder<T>(string name);        static void Main()        {            GetEmployeeHanlder<Employee> getAEmployee = GetAManager;            Employee e = getAEmployee("Mike");        }        static Manager GetAManager(string name)        {            Console.WriteLine("我是經理: " + name);            return new Manager() { Name = name };        }        static Employee GetAEmployee(string name)        {            Console.WriteLine("我是僱員: " + name);            return new Employee() { Name = name };        }    }    interface ISalary<T>    {        void Pay();    }    class BaseSalaryCounter<T> : ISalary<T>    {        public void Pay()        {            Console.WriteLine("Pay base salary");        }    }    class Employee    {        public string Name { get; set; }    }    class Programmer : Employee    {    }    class Manager : Employee    {    }

上中的GetAManager返回的是一個Manager,但是在使用中,其實是將其賦值給一個泛型參數為Employee的委託變數。因為存在下面一種情況,所以編譯不過:

            GetEmployeeHanlder<Manager> getAManager = GetAManager;            GetEmployeeHanlder<Employee> getAEmployee = GetAManager;

要讓上面的代碼編譯通過,同樣需要為委託中的泛型參數指定out關鍵字:

public delegate T GetEmployeeHanlder<out T>(string name);

除非考慮到該委託聲明肯定不會用於可變性,否則,為委託中的泛型參數指定out關鍵字將會拓展委託的應用,建議在實際編碼過程中永遠這樣使用。實際上,FCL4.0中的一些委託聲明已經用out關鍵字來讓委託支援協變了,如我們常常會使用到的:

public delegate TResult Func<out TResult>();public delegate TOutput Converter<in TInput, out TOutput>(TInput input);

 

 

 

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

 

【轉】編寫高品質代碼改善C#程式的157個建議——建議44:理解委託中的協變

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.