简体   繁体   中英

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

I have 3 classes that have almost same fields:

public DateTime Date { get; set; }

public long? Value { get; set; }

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

So for them I want to create some interface. But I don't know how to add Type field to it.

Maybe it is impossible as Enums are value types and can be derived only from System.Enum, but maybe there are some solution.

You can use generics for that:

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

Edit from the comments: If you are're already using C# 7.3, you can use where T : struct, Enum as constraint, where the Enum constrains it to enums, but since it still allow the Enum class (which is not an enum), you could keep the struct constraint as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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