如果需要的话,您可以实现自己的类结构,其中包括您从继承枚举的概念中想要的功能,还可以添加更多功能。
您只需实现相等比较器和查找值的函数即可轻松编写代码。
将构造函数设置为私有,并声明该类及其任何子类的静态实例,以任何程度都可以。
或者找到一个简单的解决方案来解决您的问题,并坚持使用本机枚举实现。
继承枚举的代码重型实现:
public class ServiceBase
{
protected int _id;
protected string _name;
private ServiceBase(int id, string name)
{
_id = id;
_name = name;
}
protected ServiceBase(int id, string name, bool isSubClass = true )
{
if( id <= _maxServiceId )
throw new InvalidProgramException("Bad Id in ServiceBase" );
_id = id;
_name = name;
}
public int Id => _id;
public string Name => _name;
public virtual ServiceBase getService(int serviceBaseId)
{
return ALLBASESERVICES.SingleOrDefault(s => s.Id == _id);
}
public static ServiceBase getServiceOrDefault(int serviceBaseId)
{
return SERVICE1.getService(serviceBaseId);
}
public static ServiceBase SERVICE1 = new ServiceBase( 1, "First Service" );
public static ServiceBase SERVICE2 = new ServiceBase( 2, "Second Service" );
protected static ServiceBase[] ALLBASESERVICES =
{
SERVICE1,
SERVICE2
};
private static int _maxServiceId = ALLBASESERVICES.Max( s => s.Id );
protected static ServiceBase[] combineServices(ServiceBase[] array1, ServiceBase[] array2)
{
List<ServiceBase> serviceBases = new List<ServiceBase>();
serviceBases.AddRange( array1 );
serviceBases.AddRange( array2 );
return serviceBases.ToArray();
}
}
public class ServiceJobs : ServiceBase
{
private ServiceJobs(int id, string name)
: base( id, name )
{
_id = id;
_name = name;
}
protected ServiceJobs(int id, string name, bool isSubClass = true )
: base( id, name )
{
if( id <= _maxServiceId )
throw new InvalidProgramException("Bad Id in ServiceJobs" );
_id = id;
_name = name;
}
public override ServiceBase getService(int serviceBaseId)
{
if (ALLSERVICES == null)
{
ALLSERVICES = combineServices(ALLBASESERVICES, ALLJOBSERVICES);
}
return ALLSERVICES.SingleOrDefault(s => s.Id == _id);
}
public static ServiceBase getServiceOrDefault(int serviceBaseId)
{
return SERVICE3.getService(serviceBaseId);
}
public static ServiceBase SERVICE3 = new ServiceJobs( 3, "Third Service" );
public static ServiceBase SERVICE4 = new ServiceJobs( 4, "Forth Service" );
private static int _maxServiceId = ALLJOBSERVICES.Max( s => s.Id );
private static ServiceBase[] ALLJOBSERVICES =
{
SERVICE3,
SERVICE4
};
private static ServiceBase[] ALLSERVICES = null;
}
请注意,您可以使用枚举而不是整数作为ID,尽管子类需要一个单独的枚举。
枚举类本身可以用各种标志、消息、函数等进行装饰。
通用实现将减少大量代码。