リフレクションを使用して、一部の 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 は、残りの道を私にもたらしました。ありがとう。