C#: cast to generic interface with base type

后端 未结 3 1859
长发绾君心
长发绾君心 2020-11-27 22:21

Here\'s the code:

public interface IValidator
{
   bool IsValid(T obj);
}

public class OrderValidator: IValidator
{
  // ...
}

public         


        
3条回答
  •  清酒与你
    2020-11-27 22:44

    Maybe it helps you if I explain why this cast is forbidden: Assume that you have the following function

    void myFunc(IValidator myValidator) {
        myValidator.IsValid(new BaseEntity());
    }
    

    This code would compile correctly. Nevertheless, if you passed an OrderValidator to this function, you would get a run-time exception, because OrderValidator.IsValid expects an Order, not a BaseEntity. Type safety would no longer be maintained if your cast were allowed.

    EDIT: C# 4 allows for generic co- and contravariance, but this would not help in your case, since you use T as an input parameter. Thus, only casting to an IValidator could be done in a type-safe way.

    So, to be clear, you cannot cast OrderValidator to IValidator because your OrderValidator can only validate orders, not all kinds of BaseEntities. This, however, is what would be expected of an IValidator.

提交回复
热议问题