从抽象派生的用户控件 class
Usercontrol derived from abstract class
我正在构建一个基于 12 个用户控件的动态 Winforms UI,这些控件可由组合框选择,并且派生自抽象 class(以提供统一的 api)。
启动所有这些大约需要 800 毫秒(太慢且无用,因为选择后只会使用一个)。但是我必须初始化它们才能访问我在组合框中显示的 public 属性 'Description'。
我想访问 属性(field, const) 静态。但这对于接口或抽象 class 是不可能的。
我可以将关系 (UserControl <-> Description) 存储在 Dictionay 中。
但是 'Description' 属于对象。
有什么方法可以 override/inherit 一个 public 静态 function/poperty/field/attribute 可以通过 interface/abstract class/Reflection 静态访问。所以我通过 interface/abstract/Reflection class 访问用户控件的描述,而不实例化派生的 class?
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));
我正在构建一个基于 12 个用户控件的动态 Winforms UI,这些控件可由组合框选择,并且派生自抽象 class(以提供统一的 api)。
启动所有这些大约需要 800 毫秒(太慢且无用,因为选择后只会使用一个)。但是我必须初始化它们才能访问我在组合框中显示的 public 属性 'Description'。
我想访问 属性(field, const) 静态。但这对于接口或抽象 class 是不可能的。
我可以将关系 (UserControl <-> Description) 存储在 Dictionay
有什么方法可以 override/inherit 一个 public 静态 function/poperty/field/attribute 可以通过 interface/abstract class/Reflection 静态访问。所以我通过 interface/abstract/Reflection class 访问用户控件的描述,而不实例化派生的 class?
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));