简体   繁体   English

从抽象类派生的用户控件

[英]Usercontrol derived from abstract class

i am building a dynamic Winforms UI based on 12 Usercontrols which are selectable by a combobox and are derived from an abstract class (to provide a unified api). 我正在基于12个用户控件构建动态Winforms UI,这些用户控件可通过组合框选择,并从抽象类派生(以提供统一的api)。

Initiating all of them takes about 800ms (much too slow and useless because only one will be used after selection). 启动所有这些程序大约需要800毫秒(太慢且无用,因为选择后将只使用其中一个)。 But i have to init them to access a public Property 'Description' which i display in the combobox. 但是我必须初始化它们才能访问显示在组合框中的公共“描述”。

I would like to access the Property(field, const) static. 我想访问Property(field,const)static。 But thats not possible with an interface or abstract class. 但这对于接口或抽象类是不可能的。

I could store the relation (UserControl <-> Description) in a Dictionay<type, string>. 我可以将关系(UserControl <-> Description)存储在Dictionay <type,string>中。 But the 'Description' belongs to the object. 但是“描述”属于对象。

Is there any way override/inherit a public static function/poperty/field/attribute which can be accessed static via an interface/abstract class/Reflection. 有什么方法可以覆盖/继承公共静态函数/属性/字段/属性,可以通过接口/抽象类/反射来静态访问该公共函数。 So i access the Description of the Usercontrol via interface/abstract/Reflection class without instantiating the derived class? 因此,我可以通过接口/抽象/反射类访问Usercontrol的描述,而无需实例化派生类?

System.Attribute is designed to do exactly this. System.Attribute旨在完全做到这一点。

For example: 例如:

[System.ComponentModel.Description("This is my fantastic control!")]
public class MyControl : UserControl
{
    //...
}

Then when you want to get the value: 然后,当您想获取值时:

public string GetDescription(Type t)
{
    System.ComponentModel.DescriptionAttribute attrib = t.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>();

    if (attrib != null)
        return attrib.Description;

    return string.Empty;
}

And to call it: 并称之为:

string myDescription = GetDescription(typeof(MyControl));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM