如何通过仅将控件作为返回类型来创建不同的控件(如文本框,标签等). [英] how to create different controls like textbox, label and etc by just having a Control as the return type.

查看:109
本文介绍了如何通过仅将控件作为返回类型来创建不同的控件(如文本框,标签等).的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过仅将控件作为返回类型来创建不同的控件(如文本框,标签等).您将代码放在哪里.

据我所知:

how to create different controls like textbox, label and etc by just having a Control as the return type. Where do you place the code.

As of what i know:

public Control this[int index]
{
  get
  {
    return (Control)List[index];
  }
}




这段代码仅返回一个控件,但我想选择要创建哪种控件.




this code returns only a control but i want to have an option which kind of control will be created.

推荐答案

Generics 可用于指定哪种<必须创建c1>,如下所示:
Generics can be used to specify which kind of Control is required to be created as shown below:
//CreateControl method used to create a TextBox and a Label
var textBox = CreateControl<TextBox>();
var label = CreateControl<Label>();

//Method to create a Control of Type T
public T CreateControl<T>() where T: new(){
    return new T();
}


您之前曾问过一个非常类似的问题:
如何将控件投射到按钮,文本框,或标签. [ 您需要某种工厂方法.然后使用指示您要获取的类型的参数调用其CreateControl函数,例如
You asked a very similar question before:
how to cast a control to button, textbox, or label.[^]
OK, now you use the word "create", but your code shows a "get" property.
You need some kind of a factory method. Then call its CreateControl function with a parameter indicating the type you want to get, e.g.
public Control CreateControl(string typeOfControl)
{
    if (typeOfControl == "TextBox")
        return new TextBox();
    if (typeOfControl == "Label")
        ...
}


我建议对要创建的控件类型使用一个枚举.
对于可以返回任何控件类型的方法,可以使用反射或VJ Reddy的CreateControl函数.


I suggest to use an enum for the types of controls which you want to create.
For a method which could return any type of Control, you would use reflection or VJ Reddy''s CreateControl function.


这篇关于如何通过仅将控件作为返回类型来创建不同的控件(如文本框,标签等).的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆