[英]Generic call to a non static method of a abstract class c#
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. 在我的代码中,我有一些枚举,例如Vehicle
, ParkingArea
等,并对其进行了扩展,以便用户可以使用默认的Vehicle和ParkingArea
值,还可以添加/更新自己的值,并将其保存在数据库中。 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
我需要使此方法成为UpdateAnyEnum
泛型,因为我不知道用户是要更新Vehicle
还是ParkingArea
在此方法中,我需要动态确定EnumExtensionForVehicle
并调用updateEnum
typeName
参数包含我尝试使用的枚举类型编辑,即Vehicle
或ParkingArea
I need to make UpdateAnyEnum
a generic method. 我需要使UpdateAnyEnum
为通用方法。 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. 通常,您需要在UpdateAnyEnum中引用EnumExtension。 And for value of T you need to make it UpdateAnyEnum generic. 对于T的值,您需要使其成为UpdateAnyEnum泛型。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.