繁体   English   中英

使用在派生类中必须具有不同枚举类型的字段创建接口

[英]Create interface with field that must have different enum types in derived classes

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

public DateTime Date { get; set; }

public long? Value { get; set; }

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

因此,我想为他们创建一些界面。 但是我不知道如何向其中添加“ Type字段。

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

您可以为此使用泛型:

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; }
}

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

暂无
暂无

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

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