lundi 29 octobre 2018

Get an instance of a generic class using Reflection (C#)

I've a container with a set of Property.

public class Property<T> : INotifyPropertyChanged
{
    private T _value;

    public Property(string name)
    {
        Name = name;
    }

    public Property(string name, T value)
        : this(name)
    {
        _value = value;
    }

    public string Name { get; }

    public T Value
    {
        get
        {
            return _value;
        }
        set
        {
            if(_value == null || !_value.Equals(value))
            {
                _value = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(Name));
                }
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

As you can see, the Property is made Generic because the type can be different. The problem is that the properties are configurable by this piece of xml:

<InputProperties> 
   <Property Type="System.UInt64" Name="Id"/>    
   <Property Type="System.DateTime" Name="Timestamp"/>   
   <Property Type="System.Byte" Name="State"/>    
</InputProperties>

So my steps should be:

1.

Initializes the container, which contains a List<Property<dynamic>> (don't like dynamic but it's the only way to solve compiling error)

2.

Parse the xml and create the generic type via reflection

foreach(XElement xProperty in allconfiguredInputParameters)
{
   string xPropertyType = xProperty.Attribute("Type") != null ? xProperty.Attribute("Type").Value : String.Empty;
   string xPropertyName = xProperty.Attribute("Name") != null ? xProperty.Attribute("Name").Value : String.Empty;

   if (!String.IsNullOrEmpty(xPropertyType) && !String.IsNullOrEmpty(xPropertyName))
   {
      Type genericProperty = typeof(Property<>);
      Type constructedGenericProperty = genericProperty.MakeGenericType(new Type[] { GetTypeByFullname(xPropertyType) });

      var property = constructedGenericProperty.GetConstructor(new Type[] { typeof(String) }).Invoke(new object[] { xPropertyName });          
    }
 }

The property as object contains the data I want but I can't cast it to Property. What I would like to do is:

myContainer.InputParamers.Add((Parameter<T>)property));

but naturally it doesn't work. Could you give me some tips? Thank you.





Aucun commentaire:

Enregistrer un commentaire