【转】编写高质量代码改善C#程序的157个建议——建议45:为泛型类型参数指定逆变

建议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个建议》陆敏技

原文地址:https://www.cnblogs.com/farmer-y/p/7988578.html