あなたは(employee.ID
対manager.MgrId
に気づく)でも、プロパティケーシングを無視して、それのためにリフレクションを使用することができます。
class Program
{
static void Main(string[] args)
{
var employee = new Employee() { ID = 1, Name = "John" };
var manager = new Manager();
foreach (PropertyInfo propertyInfo in typeof(Employee).GetProperties())
{
typeof(Manager)
.GetProperty("Mgr" + propertyInfo.Name,
BindingFlags.IgnoreCase |
BindingFlags.Instance |
BindingFlags.Public)
.SetValue(manager,
propertyInfo.GetValue(employee));
}
}
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Manager
{
public int MgrId { get; set; }
public string MgrName { get; set; }
}
あなたがMgr
接頭語がわからない場合、あなただけの一致する可能性
foreach (PropertyInfo propertyInfo in typeof(Employee).GetProperties())
{
typeof(Manager).GetMembers()
.OfType<PropertyInfo>()
.FirstOrDefault(p => p.Name.EndsWith(propertyInfo.Name,
StringComparison.CurrentCultureIgnoreCase))
.SetValue(manager,
propertyInfo.GetValue(employee));
}
そして非常に狭く、非現実的な仮定:マッピングB接尾辞によって、 (2つの型が同じ順序と数で定義されたプロパティを持つことを期待している場合、唯一の違いはプロパティ名です)。私は実際の生活の中でそれを使用して誰にもお勧めしませんが、それでも、ここにある(ただ作るために、それより壊れやすい :)):
typeof(Employee)
.GetProperties()
.Select((p, index) =>
new { Index = index, PropertyInfo = p })
.ToList()
.ForEach(p =>
{
typeof(Manager)
.GetProperties()
.Skip(p.Index)
.FirstOrDefault()
.SetValue(manager,
p.PropertyInfo.GetValue(employee));
});
*「私も任意のサードパーティ製のツールを使用したくありません。 "* 何故なの? –
反射を使用http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx –
ちょうど提案:http://automapper.org/、このようなオブジェクトを変換するための素晴らしいツールです。 –