那么和有什么区别呢?
不同之处在于in T 允许您传递比指定类型更通用(派生程度更低)的类型。
这里逆变的目的是什么?
ReSharper 建议在此处使用逆变,因为它看到您正在将 T 参数传入 Validate 方法,并希望通过使其不那么通用来扩大输入类型.
一般来说,在Contravariance explained 和Covariance and contravariance real world example 中,以及在整个 MSDN 文档中(有一个 great FAQ by the C# team),都对逆变进行了解释。
通过 MSDN 有一个很好的例子:
abstract class Shape
{
public virtual double Area { get { return 0; }}
}
class Circle : Shape
{
private double r;
public Circle(double radius) { r = radius; }
public double Radius { get { return r; }}
public override double Area { get { return Math.PI * r * r; }}
}
class ShapeAreaComparer : System.Collections.Generic.IComparer<Shape>
{
int IComparer<Shape>.Compare(Shape a, Shape b)
{
if (a == null) return b == null ? 0 : -1;
return b == null ? 1 : a.Area.CompareTo(b.Area);
}
}
class Program
{
static void Main()
{
// You can pass ShapeAreaComparer, which implements IComparer<Shape>,
// even though the constructor for SortedSet<Circle> expects
// IComparer<Circle>, because type parameter T of IComparer<T> is
// contravariant.
SortedSet<Circle> circlesByArea =
new SortedSet<Circle>(new ShapeAreaComparer())
{ new Circle(7.2), new Circle(100), null, new Circle(.01) };
foreach (Circle c in circlesByArea)
{
Console.WriteLine(c == null ? "null" : "Circle with area " + c.Area);
}
}
}
如何在这个例子中应用逆变的用法?
假设我们有自己的实体:
public class Entity : IEntity
{
public string Name { get; set; }
}
public class User : Entity
{
public string Password { get; set; }
}
我们还有一个IBusinessManager 接口和一个BusinessManager 实现,它接受IBusinessValidator:
public interface IBusinessManager<T>
{
void ManagerStuff(T entityToManage);
}
public class BusinessManager<T> : IBusinessManager<T> where T : IEntity
{
private readonly IBusinessValidator<T> validator;
public BusinessManager(IBusinessValidator<T> validator)
{
this.validator = validator;
}
public void ManagerStuff(T entityToManage)
{
// stuff.
}
}
现在,假设我们为任何 IEntity 创建了一个通用验证器:
public class BusinessValidator<T> : IBusinessValidator<T> where T : IEntity
{
public void Validate(T entity)
{
if (string.IsNullOrWhiteSpace(entity.Name))
throw new ArgumentNullException(entity.Name);
}
}
现在,我们要传递 BusinessManager<User> 和 IBusinessValidator<T>。因为它是逆变的,我可以通过BusinessValidator<Entity>。
如果我们删除 in 关键字,我们会收到以下错误:
如果我们包含它,这编译得很好。