mercredi 30 septembre 2015

Dynamically Flat C# object class List of properties at Runtime

I've a class A like that:

public class A
{
    private String id;              // Generated on server
    private DateTime timestamp;
    private int trash;
    private Humanity.FeedTypeEnum feedType
    private List<Property> properties;
// ...

where Property is:

public class Property
{
    private Humanity.PropertyTypeEnum type;
    private string key;
    private object value;
//...

I'd like to build a dynamic object that flat List<Property> properties A's field to raw properties. For example:

A a = new A();
a.Id = "Id";
a.Timestamp = DateTime.Now;
a.Trash = 2;
a.FeedType = Humanity.FeedTypeEnum.Mail;
a.Properties = new List<Property>()
{
    new Property()
    {
        Type = Humanity.PropertyTypeEnum.String,
        Key = "name"
        Value = "file1.pdf"
    },
    new Property()
    {
        Type = Humanity.PropertyTypeEnum.Timestamp,
        Key = "creationDate",
        Value = Datetime.Now
    }
}

As I've commented I'd like to flat this a object in order to access to the properties as:

String name = a.Name;
DateTime creationDate = a.CreationDate;
a.Name = "otherName";
a.CreationDate = creationDate.AddDays(1);

I've achieved that using Reflection. However, I'm figuring out that it's a best option using ExpandoObject.

The question is, how can I do that using ExpandoObject class?





Aucun commentaire:

Enregistrer un commentaire