开发者

Best loose way to get objects with common base class

开发者 https://www.devze.com 2022-12-29 13:37 出处:网络
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:

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开发者_JS百科 { 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!


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:

[DisplayName("MyAction Name")]
[Description("My description goes here")]
public class MyAction : ActionBase
{
    //Declaration goes here
}

These attributes are defined in System.ComponentModel.


You could add an abstract method to ActionBase which returns an ActionDescriptor, and then you could query each action for its descriptor.

0

精彩评论

暂无评论...
验证码 换一张
取 消