c# - 在类文件中创建控件

标签 c# winforms class

我在 C# Vis Studio Express 中选择了“类库”选项来创建一个 DLL,其中包含大量常用方法等...

我试图在类文件中创建一个文本框,这样当我将 dll 添加到另一个项目时,我必须输入的是:

MyControls.Create(TextBox);

...它将创建一个文本框并将其返回给我,然后我可以将其添加到表单中。

我知道如何创建类等,所以,我的问题是...为什么我不能使用 System.Windows.Forms 是一个类文件?我的 Class1.cs 文件中有以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyControls
{
    public class class1
    {
        public object Create(object control)
        {
            System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
            // textbox properties go here etc...

            return control;
        }
    }
}

但是红色波浪线不断告诉我“ namespace “Windows”的类型在 namespace “System”中不存在(您是否缺少程序集引用)?”

我是不是忘了在这里添加一些东西......?

谢谢:)

最佳答案

听起来好像您缺少对 System.Windows.Forms 的引用;添加该引用,您的代码应该可以正常编译。


旁注
我确实对你的方法有点好奇:

public object Create(object control)
{
    System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
    // textbox properties go here etc...

    return control;
}

输入参数有什么用?如果您不使用它,则无需传递它。另外,由于该方法应该为您创建控件,因此您可以将返回类型更改为 Control。这将消除将其添加到表单中的需要。我建议设计这样的方法(使用泛型):

public T Create<T>() where T : Control
{
    T control  = Activator.CreateInstance<T>();
    // textbox properties go here etc...

    return control;
}

关于c# - 在类文件中创建控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2171034/

相关文章:

c# - 如何在不知道 MIME 类型的情况下在 ASP.NET 中返回 FileResult?

c# - 将 Sprite x,y, width, height 转换为视口(viewport)矩形

c# - 如何将参数添加到方法并覆盖子类

.net - 带有Windows窗体的XPS

c# - 如何在 Windows.Forms 中制作 float (工具提示)控件?

javascript - 在 C# 中创建一个 JavaScript 函数

arrays - 无法使用 Swift 在 Xcode 中的类中创建数组

c# - 导致竞争条件的多线程

class - 根据一台机器上安装的类选择 puppet 模板

java - 检查数组列表中的两个对象是否相等