我正在尝试使用反射来设置某些 OpenXML 类型的属性(例如 Justification)。通过枚举所有可能性来赋值是直截了当的:
// attr is an XmlAttribute, so .Name and .Value are Strings
if (attr.Name == "Val")
{
if (element is Justification)
{
((Justification)element).Val = (JustificationValues)Enum.Parse(typeof(JustificationValues), attr.Value);
return;
}
else
{
// test for dozens of other types, such as TabStop
}
}
通过反射难以做到这一点的原因是:1) Val 属性的类型是 EnumValue<T>,所以我不知道如何提取类型作为第一个参数传递给 Enum.Parse。2) 存在从实际枚举类型到 EnumValue<> 类型的隐式转换,我不知道如何通过反射调用。
我希望代码最终看起来像:
PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = ConvertToPropType(pInfo.PropertyType, attr.Value); /* this
would return an instance of EnumValue<JustificationValues> in this case */
pInfo.SetValue(element, value, null);
如何实现 ConvertToPropType?还是有更好的解决方案?
谢谢
编辑:我得到了一个使用 Earwicker 建议的解决方案,但它依赖于枚举的类型名称可以从节点的类型名称(“Justification”->“JustificationValues”)派生的便利事实。不过,我仍然很好奇在一般情况下如何解决这个问题。
Edit2:GetGenericArguments 让我走完了剩下的路。谢谢。