コード
public class Test1
{
[Conversion("UserId")]
Public int id { get; set; }
[Conversion("UserValue")]
public int value { get; set; }
[Conversion("UserInfo")]
public List<Test2> info { get; set; }
}
public class User
{
public int UserId { get; set; }
public int UserValue { get; set; }
public List<UserInformation> UserInfo { get; set; }
}
public class Test2
{
[Conversion("UserId")]
public int id { get; set; }
[Conversion("UserName")]
public string name { get; set; }
[Conversion("UserLocation")]
public string location { get; set; }
}
public class UserInformation
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserLocation { get; set; }
}
public class ConversionAttribute
{
public string Name { get; set; }
public ConversionAttribute(string name)
{
this.Name = name;
}
}
public dynamic Convert(dynamic source, Type result)
{
var p = Activator.CreateInstance(result);
foreach (var item in source.GetType().GetProperties().Where(m => m.GetCustomAttributes(typeof(ConversionAttribute)).Count() > 0))
{
p.GetType().GetProperty(item.GetCustomAttributes(typeof(ConversionAttribute)).Cast<ConversionAttribute>().Name).Value = item.GetValue(source,null); // This should work for system types... but not for lists / custom models.
}
}
public void DoShit()
{
var t1 = new Test1 { id = 1, name = value = "Test", info = new Test2 { id = 1, name = "MyName", location = "UserLocation" } };
var obj = Convert(t1, typeof(User));
}
状況
私はデータベースモデルをWCFモデルに変換する任務を負っています。これらは、上記のサンプルコードで少し示したいくつかの点で異なります。
を使用してインスタンスを作成するActivator.CreateInstance(result)
ことができsource.GetType().GetProperties()
、すべてのプロパティをコピーするために使用できますが、モデル(カスタムクラス)またはリストに関しては問題があるようです。
問題
カスタムクラスまたはリスト(システムタイプとカスタムクラスの両方)を処理する方法がわかりません。
以前の方法では、通常の変換とリスト変換の2つの方法を使用していましたが、上司が承認しなかったため、チェックせずに使用ごとに1つの方法を使用できるかどうかを知りたいです。タイプがリスト、カスタムクラス、またはシステムタイプのいずれであるか
これが完全に汎用的であり、属性を使用する必要がある主な理由は、このメソッドを複数のプロジェクトと100を超えるモデルで使用することを計画しているためです。