我在 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/