2

クラスがあります

public class ProjectTask
{
    public ProjectTask();


    [XmlElement("task_creator_id")]
    public string task_creator_id { get; set; }
    [XmlElement("task_owner_id")]
    public string task_owner_id { get; set; }
    [XmlElement("task_owner_location")]
    public TaskOwnerLocation task_owner_location { get; set; }
    [XmlElement("task_owner_type")]
    public string task_owner_type { get; set; }
    [XmlElement("task_type_description")]
    public string task_type_description { get; set; }
    [XmlElement("task_type_id")]
    public string task_type_id { get; set; }
    [XmlElement("task_type_name")]
    public string task_type_name { get; set; }
}

xmlは実行時にこれに逆シリアル化されます。

フィールド名と値を取得する方法はありますか?

リフレクションを使用すると、次のようなプロパティ名を取得できます。

PropertyInfo[] projectAttributes = typeof(ProjectTask).GetProperties();

foreachループを適用して、プロパティを取得できます

foreach(PropertyInfo taskName in projectAttributes)
       {
           Console.WriteLine(taskName.Name);
       }

しかし、プロパティと値を出力するにはどうすればよいですか?task_creator_id=1のように

ここで、task_Idはプロパティの1つであり、実行時の値は1です。

4

2 に答える 2

1

使用する taskName.GetValue(yourObject,null)

ここyourObjectで、のインスタンスを指定する必要がありますProjectTask。たとえば、

ProjectTask yourObject = (ProjectTask)xmlSerializer.Deserialize(stream)

var propDict = typeof(ProjectTask)
                  .GetProperties()
                  .ToDictionary(p => p.Name, p => p.GetValue(yourObject, null));
于 2012-07-24T06:56:49.793 に答える
1

あなたはあなたのPropertyInfoオブジェクトを使ってそれをすることができます:

var propertyName = MyPropertyInfoObject.Name;
var propertyValue = MyPropertyInfoObject.GetValue(myObject, null);

foreachループを使用すると、タイプのすべてのプロパティにアクセスできます。また、次のように、その名前を知っている特定のプロパティを持つこともできます。

var MyPropertyInfoObject = myType.GetProperty("propertyName");
于 2012-07-24T07:20:10.737 に答える