开发者

set Enums using reflection

开发者 https://www.devze.com 2023-03-27 05:04 出处:网络
How to setEnums using reflection, my class have enum : public enum LevelEnum { NONE, CRF开发者_运维百科,

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 ?


Try use of class Enum

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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消