修正嵌入的资源用于一般的用户控件控件、用户、资源

2023-09-02 02:10:02 作者:笑面人?

在一个重构,我添加了一个泛型类型参数 MyControl ,从UserControl.所以我的课,现在 MyControl< T>

During a refactoring, I added a generic type parameter to MyControl, a class derived from UserControl. So my class is now MyControl<T>.

现在我得到一个错误,在运行时,说明该嵌入的资源文件的 MyControl&#X60; 1.resources 无法找到。就让我们来看看与 .net反射表明资源文件实际上是所谓的 MyControl.resources ,没有在&#X60; 1

Now I get an error at runtime stating that the embedded resource file MyControl`1.resources cannot be found. A quick look with .NET Reflector shows that the resource file is actually called MyControl.resources, without the `1.

在开始的 MyControl&LT; T&GT; .InitializeComponent 方法有这一行这可能是一个引起问题:

At the start of the MyControl<T>.InitializeComponent method there is this line which is probably the one causing problems:

 System.ComponentModel.ComponentResourceManager resources =
    new System.ComponentModel.ComponentResourceManager(
       typeof(MyControl<>));

我如何强制 ComponentResourceManager 使用嵌入的资源文件 MyControl.resources ?其他的方法来解决这个问题也是值得欢迎的。

How do I force the ComponentResourceManager to use the embedded resource file MyControl.resources? Other ways to resolve this issue are also welcome.

推荐答案

在除了维姆的技巧,你也可以申报非通用基础控制具有相同的名称作为通用类,和你的通用控制/表格从非通用基类派生。

In addition to Wim's technique, you can also declare a non-generic base control that has the same name as your generic class, and have your generic control/form derive from that non-generic base class.

这种方式,你可以欺骗既设计师和编译器将使用资源文件从通用类,你会得到永久的设计师的支持,一旦基类的设置,而无需在.designer文件每次你重建拨弄:

This way you can trick both the designer and the compiler into using the resource file from your generic class, and you get permanent designer support once the base class is setup without having to fiddle in the .designer file everytime you rebuild :

// Empty stub class, must be in a different file (added as a new class, not UserControl 
// or Form template)
public class MyControl : UserControl
{
}

// Generic class
public class MyControl<T> : MyControl
{
     // ...
}

唯一的要求是有完全相同的名称为您的泛型类和它的基类,基类必须在另一个类文件中,否则设计师抱怨找不到之一两班。

The only requirements are to have exactly the same name for your generic class and its base class, and that the base class must be in another class file, otherwise the designer complains about not finding one of the two classes.

PS。我测试用的形式,但它应该工作一样与控制。

PS. I tested this with forms, but it should work the same with controls.