私は次のようにオブジェクトを "deserialiazes" ジェネリックメソッドを構築した:C#のpropertyinfo用のgetValue
public class AClass
{
public int Id {get; set;}
public string Name {get;set;}
}
public class NestingClass
{
public string Address {get; set;}
List<AClass> Classes {get; set;}
}
出力場合keyvaluepairのリスト:NestingClass値:なし、AddressNestingClass値、 List1.Generic .Collections ClassesNestingClassなし、IdAClassNestingClass値、NameAClassNestingClass値。
私はすべての型を取得することができますが、値が少し難しいのは、propertyInfo.GetValue()を使用している間は常にオブジェクトを使用できないためです。たとえば、AClassのpropertyInfos(型クラスのリストを形成する)オブジェクトはAClass型でなければなりません。 「this」を使用しても動作しません。私はオブジェクトがターゲットオブジェクトと一致しない取得します。 私が必要とするのは、汎用パラメータとして渡されたオブジェクトを「スライス」し、そのような方法で値を取得しようとする何らかの仕組みです。
public List<KeyValuePair<string,string>> Process(object foo)
{
if (foo == null)
return new List<KeyValuePair<string,string>>();
var result = List<KeyValuePair<string,string>>();
var types = new Stack<Helper>();
types.Push(new Helper { Type = o.GetType(),Name = string.Empty, Value = string.Empty });
while (types.Count > 0)
{
Helper tHelper = types.Pop();
Type t = tHelper.Type;
result.Items.Add(new KeyValuePair { Key = tHelper.Name, Value = tHelper.Value });
if (t.IsValueType || t == typeof(string))
continue;
if (t.IsGenericType)
{
foreach (var arg in t.GetGenericArguments())
types.Push(new TypeHelper { Type = arg, Name = string.Empty });
continue;
}
foreach (var propertyInfo in t.GetProperties())
{
//here comes the issue
types.Push(new TypeHelper { Type = propertyInfo.PropertyType, Name = propertyInfo.Name + propertyInfo.DeclaringType.Name, Value= propertyInfo.GetValue(this,null).ToString() });
}
}
return result;
}
問題を再現するために使用できる小さなコードセットを投稿してください。 –