【问题标题】:Create interface with field that must have different enum types in derived classes使用在派生类中必须具有不同枚举类型的字段创建接口
【发布时间】:2018-11-24 06:33:38
【问题描述】:

我有 3 个类具有几乎相同的字段:

public DateTime Date { get; set; }

public long? Value { get; set; }

public (Enum1 or Enum2 or Enum3) Type { get; set; }

所以我想为他们创建一些界面。但我不知道如何添加Type 字段。

也许不可能,因为枚举是值类型,只能从 System.Enum 派生,但也许有一些解决方案。

【问题讨论】:

  • IMyInterface<T> { T Type {get;set;} } 不行吗?您可以像 Class1 : IMyInterface<Enum1> 一样使用它

标签: c# .net inheritance enums interface


【解决方案1】:

您可以为此使用泛型:

public enum TypeA { }
public enum TypeB { }
public enum TypeC { }

public interface I<T> where T : struct
{
    DateTime Date { get; set; }
    long? Value { get; set; }
    T Type { get; set; }
}

public class A : I<TypeA>
{
    DateTime Date { get; set; }
    long? Value { get; set; }
    public TypeA Type { get; set; }
}

public class B : I<TypeB>
{
    DateTime Date { get; set; }
    long? Value { get; set; }
    public TypeB Type { get; set; }
}

public class C : I<TypeC>
{
    DateTime Date { get; set; }
    long? Value { get; set; }
    public TypeC Type { get; set; }
}

从 cmets 编辑:如果您已经在使用 C# 7.3,则可以使用 where T : struct, Enum 作为约束,其中 Enum 将其约束为枚举,但由于它仍然允许Enum 类(不是枚举),您也可以保留 struct 约束。

【讨论】:

  • 最好在where T : struct类型上添加约束
  • @DavidG 很好,但使用 C# 8 更好,我认为他们会为泛型添加枚举约束。所以我们只使用where T : Enum。我在 C# 的 Build 2018 Future 中看到了它。
  • @CodeNotFound 它在 c# 7.3 中可用,但我也会保持结构约束where T : struct, Enum。
  • @CodeNotFound - where T : Enum 不幸的是允许 System.Enum 这不是枚举类型,这就是为什么仍然需要 struct 约束。
  • 它说还在用,它没有详细说明为什么,我认为这可能是一个有用的额外细节。
猜你喜欢
  • 2017-04-22
  • 2021-12-22
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 2021-08-05
  • 2013-12-20
相关资源
最近更新 更多