问题描述
|
我有一个很大的switch语句,其中基于XElement的输入值创建UIElement:
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,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.
,这样的事情可能会起作用... :)
var controlCreators = new Dictionary<string,Func<ContentControl>>
{
{\"System.Windows.Forms.Label\",() => new Label()},{\"System.Windows.Forms.Button\",() => new Button()}
};
Func<ContentControl> createControl;
if (!controlCreators.TryGetValue(element.Attribute(\"Type\").Value,out createControl))
{
return null;
}
var control = createControl();
control.Name = name;
control.Content = text;
control.Width = width;
control.Height = height;
return control;
,这些不同的控件具有继承树。因此,例如,Width,Height,Name是在FrameworkElement上定义的。因此,您可以执行以下操作:
object createdObject = null;
switch (element.Attribute(\"Type\").Value)
{
case \"System.Windows.Forms.Label\":
createdObject = new System.Windows.Controls.Label();
break;
case \"System.Windows.Forms.Button\":
createdObject = new System.Windows.Controls.Button();
break;
}
var fe = createdObject as FrameworkElement;
if (fe != null)
{
fe.Name = element.Attribute(\"Name\").Value;
fe.Width = Convert.ToDouble(element.Attribute(\"Width\").Value);
fe.Height = Convert.ToDouble(element.Attribute(\"Height\").Value);
}
var ce = createdObject as ContentElement;
if (ce != null)
{
ce.Content = element.Attribute(\"Value\").Value;
}
return createdObject;
请注意,通过这种方法,与Flynn的答案相比,您还可以轻松添加代码,例如\“当控件为ItemsControl时,执行此操作”,例如,不适用于每种类型的代码,但仅限于其中一些。
,您可以使用反射+表达式来实现。
[TestClass]
public class UnitTest1
{
public class Creator
{
private static Dictionary<string,Func<XElement,Control>> _map = new Dictionary<string,Control>>();
public static Control Create(XElement element)
{
var create = GetCreator(element.Attribute(\"Type\").Value);
return create(element);
}
private static Expression<Func<XElement,string>> CreateXmlAttributeAccessor(string elementName)
{
return (xl => xl.Attributes(elementName).Select(el => el.Value).FirstOrDefault() ?? \"_\" + elementName);
}
private static Func<XElement,Control> GetCreator(string typeName)
{
Func<XElement,Control> existing;
if (_map.TryGetValue(typeName,out existing))
return existing;
// mapping for whatever property names you wish
var propMapping = new[]
{
new{ Name = \"Name\",Getter = CreateXmlAttributeAccessor(\"Name\") },new{ Name = \"Content\",Getter = CreateXmlAttributeAccessor(\"Value\") },};
var t = Assembly.GetAssembly(typeof (Control)).GetType(\"System.Windows.Controls.\" + typeName);
var elementParameter = Expression.Parameter(typeof (XElement),\"element\");
var p = from propItem in propMapping
let member = t.GetMember(propItem.Name)
where member.Length != 0
select (MemberBinding)Expression.Bind(member[0],Expression.Invoke(propItem.Getter,elementParameter));
var expression = Expression.Lambda<Func<XElement,Control>>(
Expression.MemberInit(Expression.New(t),p),elementParameter);
existing = expression.Compile();
_map[typeName] = existing;
return existing;
}
}
[TestMethod]
public void TestMethod1()
{
var xel = new XElement(\"control\",new XAttribute(\"Type\",\"Button\"),new XAttribute(\"Name\",\"Foo\"),new XAttribute(\"Value\",\"Bar\"),new XElement(\"NonExistent\",\"foobar\")); // To check stability
var button = (Button) Creator.Create(xel);
Assert.AreEqual(\"Foo\",button.Name);
Assert.AreEqual(\"Bar\",button.Content);
}
}
要使其与其他类型(字符串除外)一起使用,可以使用Expression.Convert。留作练习。
,您可以使用反射来代替它,也可以在创建控件的地方创建一个字符串字典(现在要打开的内容)和Funcs(或动作)。
对于您发布的特定代码,您可以在switch语句后分配高度和宽度,因为它们直接存在于ѭ9上。