开发者

C#, Can I move dictionary initial code out from the constructor?

Here is my code right now. But I would like to move those "Add" out from the constructor. Can we initialize Dictionary when we new it? or you have another better idea. Basically I want to define few characters which are used in many places.

public class User
    {
        publ开发者_开发技巧ic enum actionEnum
        {
            In,
            Out,
            Fail
        }

        public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string>();

        public User()
        {
            loginAction.Add(actionEnum.In, "I");
            loginAction.Add(actionEnum.Out, "O");
            loginAction.Add(actionEnum.Fail, "F");


        }
 .....
}


You can use C# 3's collection initializer syntax:

public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string> {
    { actionEnum.In,   "I" }, 
    { actionEnum.Out,  "O" }, 
    { actionEnum.Fail, "F" }
};

Note, by the way, that the dictionary is mutable; any code can add or remove values.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜