简体   繁体   English

C#统一泛型接口和抽象类

[英]c# unity generics interface and abstract class

I have an interface : 我有一个interface

public interface IMigrationSchema<T> 
{
    T MapEvent(IOtherEvent sourceEvent);
}

implemented by an abstract class: abstract类实现:

public abstract class MigrationSchema<T> : IMigrationSchema<T>
{
    public abstract T MapEvent(IOtherEvent sourceEvent);
}

and then the actual implementation of my MigrationSchema : 然后是我的MigrationSchema的实际实现:

public class MigrationSchemaImpl: MigrationSchema<EventAfterMigration>
{
    public MigrationSchemaImpl()
        : base()
    {
    }

    public override EventAfterMigrationMapEvent(IOtherEvent actualSourceEvent)
    {
        return new EventAfterMigration(actualSourceEvent);
    }
}

knowing that: 知道:

public class EventAfterMigration : BaseEvent

What I'd like to do ideally: 我理想地要做的是:

var migrationSchema = container.Resolve<IMigrationSchema<BaseEvent>>();

and having in my config file: 并在我的配置文件中:

<register type="IMigrationSchema`1[[MyApp.BaseEvent, MyApp]]" mapTo="MigrationSchemaImpl">

I know this seems abstract, I've tested out a lot of possibilities but everytime I get the InvalidCastException , saying that the 我知道这似乎很抽象,我已经测试了很多可能性,但是每次我收到InvalidCastException时都说

MigrationSchemaImpl cannot be cast to IMigrationSchema1[BaseEvent]

I feel like this is perfectly doable but I'm missing something simple. 我觉得这完全可行,但我缺少一些简单的东西。 Any help appreciated ! 任何帮助表示赞赏!

Relationship between types does not magically become relationship between generic interfaces/types using this types. 使用这种类型,类型之间的关系不会神奇地变成通用接口/类型之间的关系。 MigrationSchemaImpl implements IMigrationSchema<EventAfterMigration> , not the IMigrationSchema<BaseEvent> - so you can't cast one to another (with or without Unity). MigrationSchemaImpl实现IMigrationSchema<EventAfterMigration>而不是IMigrationSchema<BaseEvent> -因此,您不能将一个转换为另一个(带有或不带有Unity)。

You'll get the same error with simple code: 您将通过简单的代码得到相同的错误:

var base = (IMigrationSchema<BaseEvent>)
     (new MigrationSchemaImpl());

You may try to use variance like IMigrationSchema<in BaseEvent> (not sure if it will help in your case). 您可以尝试使用方差IMigrationSchema<in BaseEvent>不知道它会在你的情况下帮助)。

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

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