获取具有公共基类的对象的最佳宽松方法
我很难为这个问题想出一个好的标题,所以欢迎提出建议。
假设我们有一个抽象基类 ActionBase,看起来像这样:
public abstract class ActionBase
{
public abstract string Name { get; }
public abstract string Description { get; }
// rest of declaration follows
}
我们定义了一堆不同的操作,如 MoveFileAction、WriteToRegistryAction 等。这些操作附加到 Worker 对象:
public class Worker
{
private IList<ActionBase> _actions = new List<ActionBase>();
public IList<ActionBase> Actions { get { return _actions; } }
// worker stuff ...
}
到目前为止,非常简单。现在,我想要一个用于设置 Workers、分配操作、设置属性等的 UI。在此 UI 中,我想呈现所有可用操作及其属性的列表,为此我想首先将可用操作(加上类型)的所有名称和描述收集到以下集合中type of item:
public class ActionDescriptor
{
public string Name { get; }
public string Description { get; }
poblic Type Type { get; }
}
当然,我可以使用反射来做到这一点,但是有更好的方法吗?让 Name 和 Description 成为 ActionBase 的实例属性(与派生类上的静态相反)有点味道,但 C# 中没有抽象静态。
谢谢你!
I struggled to come up with a good title for this question, so suggestions are welcome.
Let's say we have an abstract base class ActionBase that looks something like this:
public abstract class ActionBase
{
public abstract string Name { get; }
public abstract string Description { get; }
// rest of declaration follows
}
And we have a bunch of different actions defined, like a MoveFileAction, WriteToRegistryAction, etc. These actions get attached to Worker objects:
public class Worker
{
private IList<ActionBase> _actions = new List<ActionBase>();
public IList<ActionBase> Actions { get { return _actions; } }
// worker stuff ...
}
So far, pretty straight-forward. Now, I'd like to have a UI for setting up Workers, assigning Actions, setting properties, and so on. In this UI, I want to present a list of all available actions, along with their properties, and for that I'd want to first gather up all the names and descriptions of available actions (plus the type) into a collection of the following type of item:
public class ActionDescriptor
{
public string Name { get; }
public string Description { get; }
poblic Type Type { get; }
}
Certainly, I can use reflection to do this, but is there a better way? Having Name and Description be instance properties of ActionBase (as opposed to statics on derived classes) smells a bit, but there isn't an abstract static in C#.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所说的是为具体的 Action 类创建元数据来描述它们。对于名称和描述的简单情况,我建议使用如下所示的 DisplayName 和 Description 属性:
这些属性在
System.ComponentModel
中定义。What you're talking about is creating Metadata for your concrete Action classes to describe them. For the simple case of Name and Description, I recommend the DisplayName and Description attributes like this:
These attributes are defined in
System.ComponentModel
.您可以向 ActionBase 添加一个抽象方法,该方法返回一个 ActionDescriptor,然后您可以查询每个操作的描述符。
You could add an abstract method to ActionBase which returns an ActionDescriptor, and then you could query each action for its descriptor.