lundi 21 septembre 2015

Creating similiar classes programatically including methods

Hopefully the title, explained my question, but what I am trying to do is create classes programmatically but each one will have different properties along with methods specific to each.

Currently, each class is manually created but I would like to change that to programmatically if possible. At the moment, each class will look something like the following:

public class SomeEventName : EventBase
{

    public string HardwareId { get; set; }
    public ushort ComponantStatus { get; set; }

    public override string ToString()
    {
        return string.Format("SomeEventName event - HardwareId: {0}, GeneratedTime: {1}, ReceivedTime: {2}", HardwareId , GeneratedTime, ReceivedTime);
    }

    public static SomeEventName Default(string tvmId, DateTime createTime, DateTime receiveTime)
    {
        return new SomeEventName 
        {
            HardwareId = hardwareId,
            GeneratedTime = generatedTime,
            ReceivedTime = receivedTime,
            AdaptedTime = DateTime.UtcNow
        };
    }
}

I have substituted names but essentially

  • SomeEventName will be the name of an event
  • The properties will be specific to that event
  • The ToString override will need to substitute SomeEventName for the actual type of the class
  • The Default method will need to return an instance of the class.

I know classes can be created through code using Reflection.Emit, but when it comes to methods, I've only seen ways of doing it through IL code which I want to avoid. I could change the ToString override to use a parameter to print the class type, but I am unsure about how to handle the Default method.

The must haves are that I obviously need to be able to instantiate said classes and I need the following line of code to return the actual type and not some generic name:

typeof(SomeEventName);

Therefore, is Reflection my best bet for this and if so, is there a way to handle the Default method without having to use IL code? Or is there a different way I could approach this?





Aucun commentaire:

Enregistrer un commentaire