c# - 使用反射获取泛型类的实例
问题描述
我有一个装有一组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));
但自然是行不通的。你能给我一些建议吗?谢谢你。
解决方案
推荐阅读
- elixir - 如何从带有凤凰后端的榆树的静态资产中获取图像?
- c++ - 具有可变数量的参数的函数,这些参数被转换为字符串
- sql - 基于多个表和条件进行过滤的 SQL 命令
- python - 当我从 random.choice 行获得某行代码时,我正试图结束我的游戏
- python - Python记录端口514文件夹/yyyy/mm/dd
- sql - 将一排匹配到两排,无需替换
- python - 给定一个 1D ndarray 和一个整数,生成这个 ndarray 的最有效方法是什么?
- javascript - Paginationjs 的 Ajax 调用忽略文本字段值以进行过滤
- c++ - 单链表更新头指向自身?
- python - 如何显示用户输入的最大值和最小值?