gpt4 book ai didi

c# - 优化大型 switch 语句

转载 作者:太空狗 更新时间:2023-10-29 22:14:47 25 4
gpt4 key购买 nike

我有一个很大的 switch 语句,我在其中根据来自 XElement 的输入值创建 UIElements:

public static UIElement CreateElement(XElement element) {
var name = element.Attribute("Name").Value;
var text = element.Attribute("Value").Value;
var width = Convert.ToDouble(element.Attribute("Width").Value);
var height = Convert.ToDouble(element.Attribute("Height").Value);
//...
switch (element.Attribute("Type").Value) {
case "System.Windows.Forms.Label":
return new System.Windows.Controls.Label() {
Name = name,
Content = text,
Width = width,
Height = height
};
case "System.Windows.Forms.Button":
return new System.Windows.Controls.Button() {
Name = name,
Content = text,
Width = width,
Height = height
};
//...
default:
return null;
}
}

我正在创建很多这样的控件,如您所见,重复太多了。

有什么方法可以避免这种重复?提前感谢您的想法。

最佳答案

您可以创建一个执行创建的通用函数:

private static Create<T>(string name, string text, double width, double height) where T: Control, new()
{
return new T { Name = name, Content = text, Width = width, Height = height }
}

然后你的开关变成:

switch (element.Attribute("Type").Value) {
case "System.Windows.Forms.Label" : return Create<System.Windows.Forms.Label>(name, text, width, height);
etc.
}

您也可以根据自己的喜好调整它以传入 XElement。

如果 Type 属性始终是您想要的 System.Type 的名称,那么您可以这样做

Control ctrl = (Control) Activator.CreateInstance(Type.GetType(element.Attribute("Type").Value));
ctrl.Name = name;
etc.

如果属性的值和你想要的类型之间存在一对一的映射,那么你可以用映射声明一个只读静态字段:

private static readonly uiTypeMapping = new Dictionary<string,Type> {
{ "System.Windows.Forms.Label", typeof(System.Windows.Controls.Label) },
{ "System.Windows.Forms.Button", typeof(System.Windows.Controls.Button) },
{ etc. }
};

并使用

UIElement elem = (UIElement) Activator.CreateInstance(uiTypeMapping[element.Attribute("Type").Value]);
etc.

关于c# - 优化大型 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6094707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com