首页 > 解决方案 > 使用反射获取泛型类的实例

问题描述

我有一个装有一组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;
}

如您所见,创建属性是Generic因为类型可以不同。问题是这些属性可以通过这段 xml 配置:

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

所以我的步骤应该是:

1.

初始化容器,其中包含一个List<Property<dynamic>>(不喜欢动态但它是解决编译错误的唯一方法)

2.

解析 xml 并通过反射创建泛型类型

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 });          
    }
 }

作为对象的属性包含我想要的数据,但我无法将其转换为属性。我想做的是:

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

但自然是行不通的。你能给我一些建议吗?谢谢你。

标签: c#genericsreflectiontypescasting

解决方案


推荐阅读