名前に基づいてプロパティ値を取得する方法


147

名前に基づいてオブジェクトのプロパティの値を取得する方法はありますか?

たとえば、私が持っている場合:

public class Car : Vehicle
{
   public string Make { get; set; }
}

そして

var car = new Car { Make="Ford" };

プロパティ名を渡してプロパティ値を返すメソッドを記述したいと思います。つまり:

public string GetPropertyValue(string propertyName)
{
   return the value of the property;
}

回答:


310
return car.GetType().GetProperty(propertyName).GetValue(car, null);

17
これはリフレクションを使用するため、はるかに遅いことに注意してください。おそらく問題ではありませんが、知っておくと良いでしょう。
Matt Greer、

「文字列からBindingFlagsに変換できません」
Christine

5
@MattGreerの「より速い」方法はありますか?
FizxMike 2017

44

リフレクションを使用する必要があります

public object GetPropertyValue(object car, string propertyName)
{
   return car.GetType().GetProperties()
      .Single(pi => pi.Name == propertyName)
      .GetValue(car, null);
}

本当に凝りたいなら、それを拡張メソッドにすることができます:

public static object GetPropertyValue(this object car, string propertyName)
{
   return car.GetType().GetProperties()
      .Single(pi => pi.Name == propertyName)
      .GetValue(car, null);
}

その後:

string makeValue = (string)car.GetPropertyValue("Make");

SetValueではなくGetValueが必要です
Matt Greer

SetValueに対してもこれを行うことができますか?どうやって?
ピエロアルベルト

1
マイナーなもの-拡張メソッドはおそらく変数という名前を持つ必要はありませんcar
KyleMit 2018

propertyName文字列に基づいてプロパティ値を設定する方法については、回答を参照してください: リフレクションによるプロパティの値の設定
nwsmith

35

リフレクションが欲しい

Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);

7
+1これは、すべての中間オブジェクトを表示しているときの最良の答えです
Matt Greer

1
プロパティ値を渡す代わりに、インデックスを渡してプロパティの名前と値を取得できますか(すべてのプロパティをループできます)?
singhswat 2018年

@singhswat新しい質問としてそれを尋ねるべきです。
チャックサベージ

7

簡単なサンプル(クライアントにリフレクションハードコードを記述しない)

class Customer
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    // approach here
    public string GetPropertyValue(string propertyName)
    {
        try
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
        }
        catch { return null; }
    }
}
//use sample
static void Main(string[] args)
    {
        var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
        Console.WriteLine(customer.GetPropertyValue("CustomerName"));
    }

7

さらに、他の人が答えると、次のような拡張メソッドを使用して、オブジェクトのプロパティ値を簡単に取得できます。

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }

    }

使い方は:

Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");

7

Adam Rackisの答えを拡張すると、次のように拡張メソッドを一般的にすることができます。

public static TResult GetPropertyValue<TResult>(this object t, string propertyName)
{
    object val = t.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(t, null);
    return (TResult)val;
}

必要に応じて、エラー処理をいくつかスローすることもできます。


1

リフレクションを回避するには、プロパティ名をキーとしてディクショナリを設定し、要求したプロパティから対応する値を返すディクショナリ値部分の関数を使用します。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.