c#中switch语句的替代方法

时间:2015-08-07 09:42:41

标签: c# c#-4.0

有人可以建议另一种方法来解决这个问题,我不想在我的代码中使用SWITCH语句。

班级定义:

public class Rootobject
{
    public Must[] must { get; set; }
    public Should[] should { get; set; }        
}  

public class Should 
{
    public Match match { get; set; }
    public Bool _bool { get; set; }
}

public class Must 
{        
    public Match match { get; set; }
    public Bool _bool { get; set; }
}

public class Match
{
    public string pname { get; set; }
}

public class Bool
{
    public string rname { get; set; }
}

功能定义

public root getobject(string op)
        {
            Rootobject root = new Rootobject();

            op ="must";

            switch (op)
            {
                case "should":
                    root.should = new Should[1];
                    Should objShould = new Should();
                    objShould.match = new Match();
                    objShould.match.pname = "hello";
                    root.should[0] = objShould;
                   break;
                case "must":
                    root.must = new Must[1];
                    Must objMust = new Must();
                    objMust.match = new Match();
                    objMust.match.pname = "hello";
                    root.must[0] = objMust;
                    break;
            }                       

       return(root);
        }

Switch语句是一个新类型的开销然后我可能需要添加另一个条件。任何人都可以建议使用switch语句的替代方法。

1 个答案:

答案 0 :(得分:3)

根据您提问中的评论,我发现可以实施 @Jon Skeet 所述的内容。

您可以在 RootObject类中添加初始化方法来创建字典(使用引用字典,以避免在RootObject类中设置字典,可能会改变序列化的结构):

 public void Initialize(ref Dictionary<string, Func<Rootobject>> rootDic)
        {
            Func<Rootobject> shouldFunc = () =>
            {
                Rootobject root = new Rootobject();
                root.should = new Should[1];
                Should objShould = new Should();
                objShould.match = new Match();
                objShould.match.pname = "hello";
                root.should[0] = objShould;

                return root;
            };

            Func<Rootobject> mustFunc = () =>
            {
                Rootobject root = new Rootobject();
                root.must = new Must[1];
                Must objMust = new Must();
                objMust.match = new Match();
                objMust.match.pname = "hello";
                root.must[0] = objMust;

                return root;
            };
            rootDic.Add("should", shouldFunc);
            rootDic.Add("must", mustFunc);
        }

然后在您的 getobject方法中调用它,如下所示:

 public static Rootobject getobject(string op)
        {
            Dictionary<string, Func<Rootobject>> rootDic = new Dictionary<string,Func<Rootobject>>();
            Rootobject root = new Rootobject();
            root.Initialize(ref rootDic);

            if(rootDic.Count > 0)
            return rootDic[op].Invoke();

            return new Rootobject();
        }

即使在序列化之后,您仍然会得到与问题中的解决方案相同的结果。