我可以在C#中使用某种"类"吗?

Ton*_*ell 10 c# casting

我想知道是否可以做某事.我有一个函数,它读取一个xml文件,并根据文件中的内容向表单添加控件.像这样的xml节点将创建它:

<Button Top="300" Left="100">Automatic</Button>
Run Code Online (Sandbox Code Playgroud)

我有一个函数,如果我在编辑模式下添加任何控件,则将控件保存回xml文件.它工作正常,但我想知道是否有更简单的方法.目前,我有这样的代码来创建每个控件的实例:

            switch (xmlchild.Name)
            {
                // Create a new control whose type is specified.
                case "Button":
                    c = new Button();
                    break;
                case "Label":
                    c = new Label();
                    break;
                default:
                    c = null;
                    break;
            }
Run Code Online (Sandbox Code Playgroud)

但是,当我想使用更多类型的控件时,我需要不断添加开关案例.我可以做一些只需要文本并添加该类型控件的东西吗?我将不胜感激任何反馈!

谢谢!

LBu*_*kin 2

如果您控制 XML 文件的内容,那么可以。你可以使用:

string fullNameSpace = "System.Windows.Controls.";
Type controlType = Type.GetType( fullNameSpace + xmlchild.Name );
if( controlType != null )
{
  // get default constructor...
  ConstructorInfo ctor = controlType.GetConstructor(Type.EmptyTypes);
  object control = ctor.Invoke(null);
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用Activator该类来稍微清理一下:

object control = Activator.CreateInstance( "System.Windows.Presentation", 
                                           xmlchild.Name );
Run Code Online (Sandbox Code Playgroud)

或者,如果您可以创建有效的 XAML 文件,则可以使用 XamlReader 来恢复控件树。