I have a
FirstClass:baseClass<Entity1>; SecondClass:baseClass<Entity2> ...
The constructor of baseClass takes enum Entity, which should correspond to TEntity. Now I'm wriring enum by myself. How to make baseClass define enumEntity automatically by TEntity. Probably to use Dictionary<Entity1,enum Entity.entity1>.
CodePudding user response:
My understanding is you would like to define your different enums
, then have classes inherit from a base class that "implicitly" knows which enum to use depending on the subclass type, here FirstClass
(uses Enum1) and SecondClass
(uses Enum2).
Here's how you could achieve this. Enums are defined at the bottom, you could call them Entity1 and Entity2 if you prefer. When subclasses are created, each one will inherit of the correct enum.
The foreach
loops in the constructor are for demo purposes, just to show that the correct enum is used.
// Base class has an enum (can be any enum)
public class BaseClass<T> where T: Enum
{
public T baseClassEnum;
}
// FirstClass will inherit BaseClass enum which is here constrained to Enum1
public class FirstClass : BaseClass<Enum1>
{
public FirstClass()
{
foreach (var e in Enum.GetValues(baseClassEnum.GetType()))
{
Console.WriteLine(e);
}
}
}
// Same for SecondClass, but constrained to Enum2
public class SecondClass : BaseClass<Enum2> // This class will use Enum2
{
public SecondClass()
{
foreach (var e in Enum.GetValues(baseClassEnum.GetType()))
{
Console.WriteLine(e);
}
}
}
// Enum1 and Enum2 definitions:
public enum Enum1
{
a,
b
}
public enum Enum2
{
c,
d
}
public static void Main()
{
// Usage; note you do not specify which enum each class will have,
// as this is defined in the where contraints above:
var first = new FirstClass(); // Prints a, b as this class' enum is Enum1
var second = new SecondClass(); // Prints c, d as this class' enum is Enum2
Console.ReadKey();
}