Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 过度使用switch语句会增加开销_C#_Switch Statement - Fatal编程技术网

C# 过度使用switch语句会增加开销

C# 过度使用switch语句会增加开销,c#,switch-statement,C#,Switch Statement,我有一个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"/>

我没有太多的编码经验,所以我不确定这是否是处理这个问题的好方法。你能给我一些如何做得更好的建议吗?这里可能有一些编码模式会有所帮助?

为了使它更具有强类型(但这也会带来一些开销,因为您必须创建类),您可以为要获取的每个控件创建类,并对其进行序列化/反序列化

因此,您可以使用以下内容来代替项目,例如:

<Button action="Click" value="" />

它们都将从相同的基类继承或实现相同的接口,因此最终您将获得一个反序列化的IMyControls:)


你可以根据他们的类型做一个“切换案例”。

我建议你考虑创建一个“调度表”。您可以在这里看到一个C#示例:

如果可以重命名控件的名称以与类名匹配,则可以通过反射创建实例

string controlName = "System.Windows.Forms.Button";
Assembly assembly = typeof(Form).Assembly; 
Type type = assembly.GetType(controlName);
object controlObject = Activator.CreateInstance(type);
此外,还可以通过反射调用方法

MethodInfo methodInfo = controlObject.GetType().GetMethod("Method Name");
methodInfo.Invoke(controlObject,null);
然后返回
TableControl
,而不是
Table
,并调用/覆盖Execute命令,该命令将根据命令的类型调用特定命令


创建一个继承基本控件类的不同类型,具体取决于您要执行的操作覆盖executecommand并调用该操作。希望这有帮助

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

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

您不能序列化接口,尽管我提到过使用接口作为一种方法,将所有接口捆绑在一个集合中,然后在交换机情况下分离如何处理它们,或者做什么。但是您将如何编写序列化程序?
XmlSerializer
不接受序列化接口。它需要一个实际的对象来序列化。@默认情况下您是对的,但实际上他需要的是反序列化时间,因为问题只是从现有xml创建控件。而且,不,在序列化阶段它不会考虑接口,只是在反序列化阶段它需要知道类型,以便调用构造函数并创建实例并用数据填充它
namespace SomeNamespace {
    class Button {
    }
    public void Click(){
    }
}
//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