c#中switch语句的替代方法

Alternative for switch statement in c#

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

Class定义:

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 语句的替代方法。

根据您问题下的评论,我发现可以实现 @Jon Skeet 所说的内容。

您可以在 RootObject class 中添加一个 Initialize 方法 来创建字典(使用一个 ref 字典,以避免在你的 RootObject class 中设置字典,这可能会改变你的序列化结构 ):

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

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