這裏是一個簡單的示例,用於清除我的意圖。通過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);
}
}
}
}
我該怎麼辦?
您需要枚舉字段以及屬性。 ('type.GetFields()')。您顯示的示例類只有字段。 –
我也添加了一個屬性。 –
與主要問題沒有關係,但我認爲你應該用'if(firstModel!= null && secondModel!= null)'替代'if(firstModel!= null || secondModel!= null)' ' –