1

我熟悉 C# 中的泛型和泛型约束等,至少在我看到这个之前我是这么认为的。我在 Fluent Validation Library 中查看这个接口,它让我很震惊,这行代码是什么意思?

public interface IValidator<in T> : IValidator, IEnumerable<IValidationRule>, IEnumerable

特别是<in T>代码片段。

这是完整的界面供参考。(http://fluentvalidation.codeplex.com/SourceControl/latest#src/FluentValidation/IValidator.cs

#region 

Assembly FluentValidation.dll, v4.0.30319

#endregion

using FluentValidation.Results;
using System.Collections;
using System.Collections.Generic;

namespace FluentValidation
{
    // Summary:
    //     Defines a validator for a particualr type.
    //
    // Type parameters:
    //   T:
    public interface IValidator<in T> : IValidator, IEnumerable<IValidationRule>, IEnumerable
    {
        // Summary:
        //     Sets the cascade mode for all rules within this validator.
        CascadeMode CascadeMode { get; set; }

        // Summary:
        //     Validates the specified instance.
        //
        // Parameters:
        //   instance:
        //     The instance to validate
        //
        // Returns:
        //     A ValidationResult object containing any validation failures.
        ValidationResult Validate(T instance);
    }
}
4

4 回答 4

3

使用in关键字,T定义为逆变参数:

具有逆变类型参数的接口允许其方法接受比接口类型参数指定的派生类型更少的参数

如果您熟悉内置的委托ActionFunc. 输入参数类型ActionFunc定义为逆变

来自 MSDN 的示例:

interface IContravariant<in T> where T: class { }
class Sample<T> : IContravariant<T> { }

IContravariant<Object> iobj = new Sample<Object>();
IContravariant<String> istr = new Sample<String>();

// You can assign iobj to istr because 
// the IContravariant interface is contravariant.
istr = iobj; //compile successfully

如果您不将 T 定义为contra-vanriant,则 T 被称为invariant,并且下面的赋值将得到编译错误:

// In-variant interface. 
interface IInvariant<T> where T: class { }
class Sample<T> : IInvariant<T> where T: class { } 

IInvariant<object> iobj = new Sample<object>();
IInvariant<string> istr = new Sample<string>();

istr = iobj; // compile error

更多关于协变和逆变的信息,请点击此处

请注意,协变和逆变只支持引用类型,不支持值类型。

于 2013-05-16T14:40:00.340 回答
0

逆变是针对特定泛型类型参数强制执行的,使用 in 泛型修饰符。

http://www.codeproject.com/Articles/72467/C-4-0-Covariance-And-Contravariance-In-Generics

于 2013-05-16T14:38:12.043 回答
0

The in keyword specifies that the type parameter is contravariant. Go to below link for more details.

http://msdn.microsoft.com/en-us/library/dd469484.aspx

于 2013-05-16T14:40:07.670 回答
0

It specifies that this type parameter is a variant. Check variance and contravariance. Basically it tells the compiler that when creating a method based on this generic, in addition to the declared type, it will also accept any type that derives frpm the declared type (if it uses the word in), or any type that the declared type derives from, (if it uses the new keyword out)

于 2013-05-16T14:41:11.830 回答