Lou
Lou

Reputation: 4474

Passing class metadata through a wrapper

I would like to see if there is a way to make a wrapper class attach an attribute to itself in runtime, or any other way to inherit certain metadata from the wrapped class.

I hope this is not too long, but this is what I have:

First there is a certain class which represent a command to be sent to a device:

public interface IDeviceCommand
{
    string Name { get; }
    byte[] ToByteArray();
}

public class SomeCommand : IDeviceCommand
{ ... }

public class SomeOtherCommand : IDeviceCommand
{ ... }

Commands can be sent to the device from various places in the application, but some commands are more important than others, so I also defined a marker interface IPriorityCommand, indicating that this command should be sent immediately:

// this could also be an attribute btw
public interface IPriorityCommand { }

And my command dispatcher then checks for this:

public void SendCommand(IDeviceCommand command) 
{
    if (command is IPriorityCommand)
       SendNow(command);
    else
       Enqueue(command);
}

Also, commands can sometimes need to be wrapped to change their contents a bit, or add some other functionality:

public SomeCommandWrapper : IDeviceCommand
{
     readonly IDeviceCommand _innerCommand;
     public CommandWrapper(IDeviceCommand inner)
     { _innerCommand = inner; }

     // acts as a proxy, or changes data in a certian way
}

But now my problem is that the wrapper instance no longer implements a priority command. Also, I have several wrapper types, so it doesn't make sense to have two versions of each wrapper, different only by their interface.

I could also use an attribute instead of an interface, but I don't know how to set the attribute of the object at runtime, if it's even possible.

One additional issue is that some of these command wrappers are generic, i.e. defined in an assembly which doesn't know anything about IPriorityCommand.

Upvotes: 0

Views: 166

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

Instead of using a marker interface (IPriorityCommand) declare a property in I-IDeviceCommand such as IsHighPriority

Since the priority of the commands are defined at compile time (by implementing IPriorityCommand) you can also have the IsHighPriority attribute implementation returning true or false in SomeCommand and SomeOtherCommand

Then finally in SomeCommandWrapper, implement the IsHighPriority attribute as:

public bool IsHighPriority { get { return _innerCommand.IsHighPriority; } }

Upvotes: 1

Related Questions