C# 如何设置对象';s属性及其值(如果该对象是使用反射的列表中的对象的属性)

C# 如何设置对象';s属性及其值(如果该对象是使用反射的列表中的对象的属性),c#,reflection,C#,Reflection,我以前也有过类似的问题,但这个问题需要不同的解决方案 我的模型上有对象,服务上有对象 如果两个对象的属性相同,我需要将模型的对象属性值设置为来自服务的列表的属性值 这是一个模型: public class MyModel{ public ObjectAEntity ObjectAData { get; set; } public ObjectBEntity ObjectBData { get; set; } } ObjectAEntity有一个名为“SalesAmount

我以前也有过类似的问题,但这个问题需要不同的解决方案

我的模型上有对象,服务上有对象

如果两个对象的属性相同,我需要将模型的对象属性值设置为来自服务的
列表的属性值

这是一个模型:

public class MyModel{

     public ObjectAEntity ObjectAData { get; set; }
     public ObjectBEntity ObjectBData { get; set; }
}
ObjectAEntity
有一个名为“SalesAmount”的属性

这是一项服务:

public class MyScreenClass
{
     public List<TicketReportPropertyEntity> TicketReportPropertyEntities { get; set; } 
}

public class TicketReportPropertyEntity
{
    public decimal Amount{get;set;}
    public ReportPropertyEntity ReportProperty {get;set;}
} 

public class ReportPropertyEntity
{
    public string ReportGroup { get; set; }        
    public string PropertyName { get; set; }
}

我怎样才能做到这一点呢?

要做到这一点,您可以尝试通过当前
TicketReportPropertyEntity.ReportPropertyEntity.PropertyName
中存储的
字符串
值来获取属性。因为您已经有了很多这样的设置,所以只需要再编写几行代码

//here I need to find out if the ObjectAEntity has the same property as ReportProperty

//Attempt to grab the PropertyInfo that you want to set
var objectAEntityReportProperty = bo.GetType().GetProperty(reportPropertyNameValue);

//If it is not null, you have found a match
var has = objectAEntityReportProperty != null;
if (has)
{
    //need to set the value of the Model's `ObjectAEntity` property
    //Then, set the value
    objectAEntityReportProperty.SetValue(bo, ticketReportEntity.Amount);
}

现在代码没有编译。
m
变量是一个
MyModel
对象,但您试图使用该类中不存在的
TicketReportPropertyEntities
属性。你能更正代码吗?如果我们试图推断你想做什么,我们可能会弄错。更改它。我用了不同的物体。我需要了解ObjectAEntity是否拥有ReportProperty Objects的财产谢谢您的支持help@gene不客气!我希望你能在需要的地方得到它。
//here I need to find out if the ObjectAEntity has the same property as ReportProperty

//Attempt to grab the PropertyInfo that you want to set
var objectAEntityReportProperty = bo.GetType().GetProperty(reportPropertyNameValue);

//If it is not null, you have found a match
var has = objectAEntityReportProperty != null;
if (has)
{
    //need to set the value of the Model's `ObjectAEntity` property
    //Then, set the value
    objectAEntityReportProperty.SetValue(bo, ticketReportEntity.Amount);
}