我在C#Vis Studio Express中选择了Class Library选项来创建一个DLL,它包含了我常用的方法等等......
我正在尝试在类文件中创建一个文本框,这样当我将dll添加到另一个项目时,我必须输入的是:
MyControls.Create(文本框);
...它会创建一个文本框并将其返回给我,然后我可以将其添加到表单中。
我知道如何创建类等,所以,我的问题是...为什么我不能使用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;
}
}
}
但是红色的线条不断告诉我“命名空间'Windows'的类型在命名空间'System'中不存在(你是否缺少程序集引用)?”
我忘了在这里添加一些东西...... ??
谢谢:)
答案 0 :(得分:2)
听起来好像你错过了对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;
}
答案 1 :(得分:1)
是的,你必须在项目的引用中添加对winforms dll(System.Windows.Forms)的引用。当你创建一个win表单应用程序时,这会自动发生,但是因为你只是一个dll而不是那里。
答案 2 :(得分:1)
添加参考。因为您创建了一个类库而不是一个表单项目,所以没有必要的库引用。转到Project菜单&gt; Add Reference ...并从.NET选项卡中选择System.Windows.Forms。
答案 3 :(得分:0)
如上所述,添加对System.Windows.Forms
的引用就足够了。
虽然我个人并不喜欢在同一个程序集中混合使用公共类和控件,而是为非GUI代码添加一个或多个项目以及纯GUI代码的另一个项目。