我有一个 abstract 具有类型约束的类。但我也想做 abstract 类实现一个接口。

例如:

public abstract class PostEvent<TPost> : IDomainEvent, where TPost : Post, new()

它不能编译。

我不想这样:

public abstract class PostEvent<TPost> where TPost : Post, IDomainEvent, new()

因为这意味着 TPost : IDomainEvent

我要 PostEvent : IDomainEvent

语法是什么?

有帮助吗?

解决方案

试试这个:

public abstract class PostEvent<TPost> : IDomainEvent where TPost : Post, new() 

您不希望在接口列表和泛型约束之间使用逗号。

其他提示

你需要实际实现它(你不能离开实现 纯粹的 到具体类型-它需要知道从哪里开始):

public abstract class PostEvent<TPost> : IDomainEvent
    where TPost : Post, new()
{
    public abstract void SomeInterfaceMethod();
}

如果您不想在公共API上使用Otis,您也可以使用显式接口实现和受保护的抽象方法:

public abstract class PostEvent<TPost> : IDomainEvent
    where TPost : Post, new()
{
    protected abstract void SomeInterfaceMethod();
    void IDomainEvent.SomeInterfaceMethod() {
        SomeInterfaceMethod(); // proxy to the protected abstract version
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top