假设我有以下三个类/接口:
public interface IImportviewmodel { } public class TestImportviewmodel : IImportviewmodel { } public class ValidationResult<Tviewmodel> where Tviewmodel : IImportviewmodel { }
由于TestImportviewmodel实现了IImportviewmodel,为什么以下不能编译?
ValidationResult<IImportviewmodel> r = new ValidationResult<TestImportviewmodel>();
我理解错误消息“无法将类型’ValidationResult’隐式转换为’ValidationResult’”的含义.我只是不明白为什么会这样.这不是协方差吗?
解决方法
Would this not be covariance?
是的,除了在C#4.0中协方差仅适用于接口.因此,您必须使ValidationResult实现一个协变接口(通用参数定义为out):
public interface IImportviewmodel { } public class TestImportviewmodel : IImportviewmodel { } public interface IValidationResult<out Tviewmodel> where Tviewmodel : IImportviewmodel { } public class ValidationResult<Tviewmodel> : IValidationResult<Tviewmodel> where Tviewmodel : IImportviewmodel { }
现在你可以这样做:
IValidationResult<IImportviewmodel> r = new ValidationResult<TestImportviewmodel>();