set Enums using reflection

扶醉桌前 提交于 2019-12-05 08:28:25
public class MyObject
{
    public LevelEnum MyValue {get;set,};
}


var obj = new MyObject();
obj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);

Try use of class Enum

LevelEnum s = (LevelEnum)Enum.Parse(typeof(LevelEnum), "CDD");
value = (LevelEnum)Enum.Parse(typeof(LevelEnum),"CDD");

So basically you just parse the string corresponding to the enum value that you wish to assign to the variable. This will blow if the string is not a defined member of the enum. you can check that with Enum.IsDefined(typeof(LevelEnum),input);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!