In my code I have enums like Vehicle
, ParkingArea
etc. and I have extended them so that the user can make use of the default Vehicle and ParkingArea
values and also add/update their own which gets saved in the database. I have a abstract class like so ,
public abstract class EnumExtension<T> where T : struct
{
public bool updateEnum(string name){
//code to update the enum extension
}
}
And there is a controller like the following to access the above update method
public class MyController : ApiController
{
public void UpdateAnyEnum(string newName, int value, string typeName){
var enum_1 = (EnumExtensionForVehicle)value;
enum_1.updateEnum(newName);
}
}
I need to make this method UpdateAnyEnum
generic since I do not know whether the user is trying to update the Vehicle
or ParkingArea
In this method I need to determine EnumExtensionForVehicle
dynamically and make a call to updateEnum
The typeName
parameter consists the type of enum I am trying to edit ie either Vehicle
or ParkingArea
I need to make UpdateAnyEnum
a generic method. Any thoughts and ideas are much appreciated. Thank you.
I am not sure how you determine the class to call. In general you need a reference of EnumExtension in UpdateAnyEnum. And for value of T you need to make it UpdateAnyEnum generic. Something like below.
Note: Below code is not tested. Its just an idea of how code should work
public abstract class EnumExtension<T> where T : struct
{
public bool updateEnum(string name){
//code to update the enum extension
}
}
public class EnumExtensionForVehicle : EnumExtension<Vehicle>
{
public bool updateEnum(string name){
//code to update the enum extension
}
}
public class EnumExtensionForParkingArea : EnumExtension<ParkingArea>
{
public bool updateEnum(string name){
//code to update the enum extension
}
}
public class MyController : ApiController
{
public void UpdateAnyEnum<T>(string newName, int value, string typeName) {
EnumExtension<T> factory;
switch (typeName)
{
case "Vehicle":
factory = new EnumExtensionForVehicle();
break;
case "ParkingArea":
factory = new EnumExtensionForParkingArea();
break;
}
factory.updateEnum(newName);
}
}
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.