set Enums using reflection

非 Y 不嫁゛ 提交于 2019-12-22 07:03:17

问题


How to set Enums using reflection,

my class have enum :

public enum LevelEnum
    {
        NONE,
        CRF,
        SRS,
        HLD,
        CDD,
        CRS
    };

and in runtime I want to set that enum to CDD for ex.

How can I do it ?


回答1:


public class MyObject
{
    public LevelEnum MyValue {get;set,};
}


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



回答2:


Try use of class Enum

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



回答3:


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);



来源:https://stackoverflow.com/questions/7009958/set-enums-using-reflection

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