【问题标题】:How to specify type constraint and inheritance on declaring class?如何在声明类时指定类型约束和继承?
【发布时间】:2012-03-12 23:53:04
【问题描述】:

我有一个具有类型约束的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

语法是什么?

【问题讨论】:

  • 我目前没有设置来测试它,但您可以尝试删除IDomainEventwhere 之间的逗号。

标签: c# generics c#-4.0 interface type-constraints


【解决方案1】:

试试这个:

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

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

【讨论】:

    【解决方案2】:

    您需要实际实现它(您不能将实现纯粹留给具体类型 - 它需要知道从哪里开始):

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

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

    public abstract class PostEvent<TPost> : IDomainEvent
        where TPost : Post, new()
    {
        protected abstract void SomeInterfaceMethod();
        void IDomainEvent.SomeInterfaceMethod() {
            SomeInterfaceMethod(); // proxy to the protected abstract version
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多