1
[XmlElement(ElementName = "SalesStageId", Form = XmlSchemaForm.None)]
public EntityIdentifier OpportunitySalesStageId { get; set; }

上記のメソッド名はElementNameです。"SalesStageId""OpportunitySalesStageId"

上記のメソッドを含むクラスのオブジェクトを介して、要素名からメソッド名を見つける方法はありますか。

4

1 に答える 1

1
  1. リフレクションを使用して型のプロパティを取得するType.GetProperties()
  2. PropertyInfo次に、カスタム属性XmlElementAttributeをそれぞれ検索できますPropertyInfo.GetCustomAttribute
  3. 属性が見つかった (つまり、null でない) 場合は、単純にその内容をクエリして、一致するかどうかを確認できます。
  4. 残りのプロパティについて、手順 2 と 3 を繰り返します。

プログラム例:

(LINQ と拡張メソッドで最適化)

using System;
using System.Linq;
using System.Reflection;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string propName = FindPropertyNameByXmlElementAttributeElementName(typeof (MyClass), "Foo");

            Console.WriteLine(propName);
            Console.ReadKey();
        }
        static string FindPropertyNameByXmlElementAttributeElementName(Type type, string elementName)
        {
            PropertyInfo propertyInfo = 
                type.GetProperties().SingleOrDefault(
                        prop => prop.HasAttributeWithValue<XmlElementAttribute>(
                                a => a.ElementName == elementName
                            )
                    );
            if (propertyInfo == null)
            {
                return "NOT FOUND";
            }
            return propertyInfo.Name;
        }
    }

    public static class PropertyInfoExtensions
    {
        public static bool HasAttributeWithValue<TAttribute>(this PropertyInfo pi, Func<TAttribute, bool> hasValue)
        {
            TAttribute attribute = 
                (TAttribute)pi.GetCustomAttributes(typeof(TAttribute), true).SingleOrDefault();
            if (attribute == null)
            {
                return false;
            }
            return hasValue(attribute);
        }
    }
    class MyClass
    {
        [XmlElement(ElementName = "Foo", Form = XmlSchemaForm.None)]
        public string Rumplestiltskin { get; set; }
    }
}
于 2013-02-05T22:37:22.063 に答える