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



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

public DateTime Date { get; set; }
public long? Value { get; set; }
public (Enum1 or Enum2 or Enum3) Type { get; set; }

所以对于他们,我想创建一些界面。但是我不知道如何向其添加Type字段。

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

你可以为此使用泛型:

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约束。

最新更新