はいあります。私は自分のプロジェクトで、特定のオブジェクトのマクロのすべての文字列プロパティを解析するマクロ パーサーを作成しました。SetValue
リフレクションを使用してオブジェクトのプロパティを反復処理し、適切なプロパティでメソッドを呼び出すという考え方です。
その日の最初の注文(私にとって)は、次の拡張メソッドを作成することでしたSystem.Type
:
public static partial class TypeExtensionMethods
{
public static PropertyInfo[] GetPublicProperties(this Type self)
{
return self.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where((property) => property.GetIndexParameters().Length == 0 && property.CanRead && property.CanWrite).ToArray();
} // eo GetPublicProperties
} // eo class TypeExtensionMethods
そして、それをオブジェクトで使用します(注、ForEach
は拡張メソッドですが、の省略形ですfor each()
:
obj.GetType().GetPublicProperties().ForEach((property) =>
{
if (property.GetGetMethod().ReturnType == typeof(string))
{
string value = (string)property.GetValue(obj, null);
if (value == null)
property.SetValue(obj, string.Empty, null);
}
}