加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 过度使用switch语句开销

发布时间:2020-12-15 21:46:12 所属栏目:百科 来源:网络整理
导读:我有xml文件,其中包含必须在html控件上执行的特定步骤和操作: Item control="Dropdown" action="Click" value=""/Item control="Button" action="GetText" value=""/Item control="Input" action="WriteText" value="Sample Text"/ 我将使用很多控件,每个控
我有xml文件,其中包含必须在html控件上执行的特定步骤和操作:

<Item control="Dropdown" action="Click" value=""/>
<Item control="Button" action="GetText" value=""/>
<Item control="Input" action="WriteText" value="Sample Text"/>

我将使用很多控件,每个控件都有几个方法,如Click,GetText,Exsists ..

目前我使用开关来处理它,但我听说这不是一个好习惯.我有一个开关来选择特定的控制,每个控件都切换到调用特定的方法.

switch (control)
            {
                case "button":
                    return new Button;
                case "table":
                    return new Table;
                (...)
            }

(...)


        switch (action)
        {
            case "click":
                this.Click();
                return true;
            case "gettext":
                this.GetText();
                return true;
            default:
                return false;
        }

我没有太多的编码经验,所以我不确定这是否是处理这个问题的好方法.你能给我一些建议怎么做得更好吗?也许有一些编码模式在这里有用吗?

解决方法

你可以为你拥有的每种控件创建一个类

namespace SomeNamespace {
    class Button {
    }
    public void Click(){
    }
}

然后当你阅读XML

//assemblyName is the full name of the assembly holding your control classes
var type = System.GetType(assemblyName,"SomeNamespace." + control);
var control = Activator.CreateInstance(type); //requires a default constructor
type.GetMethod(methodName).Invoke(control); //methodName could be click

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读