不明なオブジェクトからプロパティと値を取得する


150

PHPの世界から、C#を試すことにしました。私は検索をしましたが、これと同等のことをする方法の答えを見つけることができないようです。

$object = new Object();

$vars = get_class_vars(get_class($object));

foreach($vars as $var)
{
    doSomething($object->$var);
}

基本的にオブジェクトのリストがあります。オブジェクトは3つの異なるタイプのいずれかであり、一連のパブリックプロパティを持ちます。オブジェクトのプロパティのリストを取得し、それらをループしてファイルに書き込めるようにしたいのですが。これはc#リフレクションに関係していると思いますが、それは私にとってすべて新しいものです。

どんな助けでも大歓迎です。


9
余談ですが、リストにさまざまなタイプのオブジェクト(共通の基本クラスまたはインターフェースなし)を含めることは、少なくともc#では、良いプログラミングスタイルではありません。
Albin Sunnanbo、2010年

回答:


284

これはそれを行うはずです:

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    object propValue = prop.GetValue(myObject, null);

    // Do something with propValue
}

PropertyInfoはどこから来たのですか?
ジョナサン

8
@jonathan System.Reflection名前空間
Cocowalla 2013年

21
単に配列からリストを作成する必要はまったくありませんPropertyInfo[] props = input.GetType().GetProperties();
VladL

2
2017年の回答を使用して更新しNewtonsoft.Json.JsonConvertますか?
ヴェイン2017

1
@cloneは完全に別の方法です。有効なアプローチだと思われる場合は、回答を投稿してください
Cocowalla

23
void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

17

はい、リフレクションは行くべき道でしょう。まず、Typeリストのインスタンスのタイプ(実行時)を表すを取得します。これを行うには、のGetTypeメソッドをObject呼び出します。これはObjectクラス上にあるため、すべての型の派生元として、.NETのすべてのオブジェクトから呼び出すことができますObject技術的にはすべてはありませんが、ここでは重要ではありません)。

あなたが持ってたらType、インスタンスを、あなたが呼び出すことができるGetProperties方法を取得するにはPropertyInfo上のプロパティに関する実行時informationaを表すインスタンスをType

のオーバーロードを使用して、取得GetPropertiesするプロパティを分類することができます。

そこから、情報をファイルに書き出すだけです。

上記のコードを翻訳すると、次のようになります。

// The instance, it can be of any type.
object o = <some object>;

// Get the type.
Type type = o.GetType();

// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
    // Do something with the property info.
    DoSomething(info);
}

メソッド情報またはフィールド情報が必要な場合は、GetMethodsまたはGetFieldsメソッドのオーバーロードの1つをそれぞれ呼び出す必要があることに注意してください。

また、メンバーをファイルにリストすることは1つのことですが、この情報を使用して、プロパティセットに基づいてロジックを駆動しないでください。

タイプの実装を制御できると仮定すると、共通の基本クラスから派生するか、共通のインターフェースを実装し、それらに対して呼び出しを行う必要があります(asまたはis演算子を使用して、操作している基本クラス/インターフェースを特定するのに役立ちますランタイム)。

ただし、これらの型定義を制御せず、パターンマッチングに基づいてロジックを駆動する必要がある場合は、問題ありません。


11

まあ、C#でも同様です。これが最も単純な例の1つです(パブリックプロパティのみ)。

var someObject = new { .../*properties*/... };
var propertyInfos = someObject.GetType().GetProperties();
foreach (PropertyInfo pInfo in PropertyInfos)
{
    string propertyName = pInfo.Name; //gets the name of the property
    doSomething(pInfo.GetValue(someObject,null));
}

9

プロパティ名から特定のプロパティ値を取得するには

public class Bike{
public string Name {get;set;}
}

Bike b = new Bike {Name = "MyBike"};

プロパティの文字列名からNameのプロパティ値にアクセスする

public object GetPropertyValue(string propertyName)
{
//returns value of property Name
return this.GetType().GetProperty(propertyName).GetValue(this, null);
} 

3

GetType-GetProperties-Linq Foreachを使用できます。

obj.GetType().GetProperties().ToList().ForEach(p =>{
                                                        //p is each PropertyInfo
                                                        DoSomething(p);
                                                    });

3

Linqを使用した1行のソリューション...

var obj = new {Property1: 1, Property2: 2};
var property1 = obj.GetType().GetProperties().First(o => o.Name == "Property1").GetValue(obj , null);

2

ここで私は変換するために使用する何かIEnumerable<T>DataTable表現する列が含まれていることTで項目ごとに1行で、のプロパティをIEnumerable

public static DataTable ToDataTable<T>(IEnumerable<T> items)
{
    var table = CreateDataTableForPropertiesOfType<T>();
    PropertyInfo[] piT = typeof(T).GetProperties();
    foreach (var item in items)
    {
        var dr = table.NewRow();
        for (int property = 0; property < table.Columns.Count; property++)
        {
            if (piT[property].CanRead)
            {
                var value = piT[property].GetValue(item, null);
                if (piT[property].PropertyType.IsGenericType)
                {
                    if (value == null)
                    {
                        dr[property] = DBNull.Value;
                    }
                    else
                    {
                        dr[property] = piT[property].GetValue(item, null);
                    }
                }
                else
                {
                    dr[property] = piT[property].GetValue(item, null);
                }
            }
        }
        table.Rows.Add(dr);
    }
    return table;
}

public static DataTable CreateDataTableForPropertiesOfType<T>()
{
    DataTable dt = new DataTable();
    PropertyInfo[] piT = typeof(T).GetProperties();
    foreach (PropertyInfo pi in piT)
    {
        Type propertyType = null;
        if (pi.PropertyType.IsGenericType)
        {
            propertyType = pi.PropertyType.GetGenericArguments()[0];
        }
        else
        {
            propertyType = pi.PropertyType;
        }
        DataColumn dc = new DataColumn(pi.Name, propertyType);

        if (pi.CanRead)
        {
            dt.Columns.Add(dc);
        }
    }
    return dt;
}

これは「やや」複雑すぎますがList<T>、たとえば次のようにして結果を確認できるので、結果を確認するのに非常に適しています。

public class Car
{
    string Make { get; set; }
    int YearOfManufacture {get; set; }
}

そして、次の構造のDataTableが返されます。

Make(文字列)
YearOfManufacture(int)

あなたのアイテムごとに1行で List<Car>


1

この例では、オブジェクトのすべての文字列プロパティをトリミングします。

public static void TrimModelProperties(Type type, object obj)
{
    var propertyInfoArray = type.GetProperties(
                                    BindingFlags.Public | 
                                    BindingFlags.Instance);
    foreach (var propertyInfo in propertyInfoArray)
    {
        var propValue = propertyInfo.GetValue(obj, null);
        if (propValue == null) 
            continue;
        if (propValue.GetType().Name == "String")
            propertyInfo.SetValue(
                             obj, 
                             ((string)propValue).Trim(), 
                             null);
    }
}

0

私はこれが動作することを発見していません、例えばアプリケーションオブジェクト。しかし、私は成功しました

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

string rval = serializer.Serialize(myAppObj);

2
回避できる場合は、JavaScriptSerializerを使用しないでください。多くの理由があります
ヌーノ・アンドレ

0
public Dictionary<string, string> ToDictionary(object obj)
{
    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    Type objectType = obj.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(objectType.GetProperties());

    foreach (PropertyInfo prop in props)
    {
        object propValue = prop.GetValue(obj, null);
        dictionary.Add(prop.Name, propValue.ToString());
    }

    return dictionary;
}

0
    /// get set value field in object to object new (two object  field like ) 

    public static void SetValueObjectToObject (object sourceObj , object resultObj)
    {
        IList<PropertyInfo> props = new List<PropertyInfo>(sourceObj.GetType().GetProperties());
        foreach (PropertyInfo prop in props)
        {
            try
            {
                //get value in sourceObj
                object propValue = prop.GetValue(sourceObj, null);
                //set value in resultObj
                PropertyInfo propResult = resultObj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
                if (propResult != null && propResult.CanWrite)
                {
                    propResult.SetValue(resultObj, propValue, null);
                }
            }
            catch (Exception ex)
            {  
                // do something with Ex
            }
        }
    }

-1

あなたはこれを試すことができます:

string[] arr = ((IEnumerable)obj).Cast<object>()
                                 .Select(x => x.ToString())
                                 .ToArray();

すべての配列がIEnumerableインターフェイスを実装したら

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