简体   繁体   English

将类转换为具有泛型类型的接口时出错(同时将泛型类型转换为其基类时)

[英]Error casting class to its interface with generic type (when also casting generic type to its base)

Hello I have the next problem casting classes.你好,我有下一个问题铸造类。 I have a Quest class that others inherit我有一个别人继承的 Quest 课程

public class Quest{}

public class QuestChild: Quest{}

I use a generic validator that expects to receive some type of Quest我使用了一个通用验证器,它希望收到某种类型的 Quest

public interface IQuestValidator<in T> where T:Quest
{
    bool IsCompleted(T quest);

    bool IsFailed(T quest);
}

public class QuestValidator<T>: IQuestValidator<T> where T: Quest
{    
    public bool IsCompleted(T quest)
    {
        return false;
    }

    public bool IsFailed(T quest)
    {
        return true;
    }
}

When I create the validator for each derived class of Quest, I want to cast it to its Base clase like this:当我为 Quest 的每个派生类创建验证器时,我想将它转换为它的 Base 类,如下所示:

    IQuestValidator<Quest> c = (IQuestValidator<Quest>)new QuestValidator<QuestChild>();

But when I execute this line, it returns the error "InvalidCastException".但是当我执行这一行时,它返回错误“InvalidCastException”。 Why this happens or how could I solve this to cast correctly?为什么会发生这种情况,或者我如何解决这个问题以正确投射?

Note: It seems similar to this question C# variance problem: Assigning List<Derived> as List<Base> , but since I'm not using IEnumerable I can't do the same.注意:这似乎类似于这个问题C# 方差问题:将 List<Derived> 分配为 List<Base> ,但由于我没有使用 IEnumerable,我不能这样做。

The corresponding class is invariant, so there's no way the cast would be possible!相应的类是不变的,所以不可能进行强制转换! Try rethinking your design to remove the demand for the desired cast.尝试重新考虑您的设计以消除对所需演员的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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