开发者

set Enums using reflection

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜