简体   繁体   中英

How do I cast this generic interface?

I have the following classes defined to do validation:

public class DefValidator : IValidate<IDef>
{
}

public interface IDef : IAttribute
{
}

Then, I have a list of validators defined as so:

IList<IValidate<IAttribute>> ValidationObjects;

When I try the following, it doesn't compile saying it can't convert types.

DefValidator defv = new DefValidator();
ValidationObjects.Add(defv);

When I try the following, it compiles but generates an exception saying "unable to cast object".

ValidationObjects.Add((IValidate<IAttribute>)defv);

Any ideas?

您的问题与协方差/协方差有关,请参见如何在C#4.0中实现通用协方差和反方差?

This is a subtle issue to do with co and contra-variance in generics; there are many simpler examples of this on SO. Essentially, types within generics have to match exactly to be compatible, they can't be subclasses or superclasses.

To get it to compile, ValidationObjects needs to be IList<IValidate<IDef>>, or DefValidator needs to inherit off IValidate<IAttribute>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM