从抽象类

时间:2015-05-07 11:27:52

标签: c# winforms user-controls

我正在构建一个基于12个Usercontrol的动态Winforms UI,这些UI可以通过组合框选择并从抽象类派生(以提供统一的api)。

启动所有这些操作大约需要800毫秒(太慢而且无用,因为选择后只会使用一个)。但我必须让他们访问公共财产'描述'我在组合框中显示。

我想访问Property(field,const)static。但这对于接口或抽象类来说是不可能的。

我可以在Dictionay< type,string>中存储关系(UserControl< - > Description)。 但是'描述'属于对象。

是否有任何方式覆盖/继承可以通过接口/抽象类/ Reflection静态访问的公共静态函数/ poperty / field / attribute。所以我通过interface / abstract / Reflection类访问Usercontrol的描述而不实例化派生类?

1 个答案:

答案 0 :(得分:1)

System.Attribute正是为此而设计的。

例如:

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

然后当你想得到这个值时:

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

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

    return string.Empty;
}

并称之为:

string myDescription = GetDescription(typeof(MyControl));

相关问题