2012-06-28 60 views
0

這裏是一個簡單的示例,用於清除我的意圖。通過GetProperties將屬性從一個類設置爲另一個類

class A { 
    public int Id 
    public string Name 
    public string Hash 
    public C c 
} 
class B { 
    public int id 
    public string name 
    public C c 
} 
class C { 
    public string name 
} 
var a = new A() { Id = 123, Name = "something", Hash = "somehash" }; 
var b = new B(); 

我想從a設置b的屬性。我嘗試了一些,但沒有運氣。

public void GenericClassMatcher(object firstModel, object secondModel) 
    { 
     if (firstModel != null || secondModel != null) 
     { 
      var firstModelType = firstModel.GetType(); 
      var secondModelType = secondModel.GetType(); 
      // to view model 
      foreach (PropertyInfo prop in firstModelType.GetProperties()) 
      { 
       var firstModelPropName = prop.Name.ElementAt(0).ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture) + prop.Name.Substring(1); // lowercase first letter 
       if (prop.PropertyType.FullName.EndsWith("Model")) 
       { 
        GenericClassMatcher(prop, secondModelType.GetProperty(firstModelPropName)); 
       } 
       else 
       { 
        var firstModelPropValue = prop.GetValue(firstModel, null); 
        var secondModelProp = secondModelType.GetProperty(firstModelPropName); 
        if (prop.PropertyType.Name == "Guid") 
        { 
         firstModelPropValue = firstModelPropValue.ToString(); 
        } 
        secondModelProp.SetValue(secondModel, firstModelPropValue, null); 
       } 
      } 
     } 
    } 

我該怎麼辦?

+1

您需要枚舉字段以及屬性。 ('type.GetFields()')。您顯示的示例類只有字段。 –

+0

我也添加了一個屬性。 –

+1

與主要問題沒有關係,但我認爲你應該用'if(firstModel!= null && secondModel!= null)'替代'if(firstModel!= null || secondModel!= null)' ' –

回答

1

這聽起來像你試圖地圖一類到另一個。 AutoMapper是我遇到過的最好的工具。

public class A 
    { 
     public int Id; 
     public string Name; 
     public string Hash; 
     public C c; 
    } 

    public class B 
    { 
     public int id; 
     public string name; 
     public C c; 
    } 

    public class C 
    { 
     public string name; 
    } 


    class Program 
    { 
     static void Main(string[] args) 
     { 
      var a = new A() { Id = 123, Name = "something", Hash = "somehash" }; 
      var b = new B(); 

      AutoMapper.Mapper.CreateMap<A, B>(); 

      b = AutoMapper.Mapper.Map<A, B>(a); 


      Console.WriteLine(b.id); 
      Console.WriteLine(b.name); 

      Console.ReadLine(); 
     } 
} 
+0

是的,但我需要在映射之前轉換字段名稱。 –

+0

@fastreload根據您的問題,我無法確定您需要進行哪種轉換,但AutoMapper可以處理它。 – cadrell0

+0

在AutoMapper中有很好的lambda語法。爲你做一個樣本。 –

相關問題