尝试使用SetValue时,对象与目标类型不匹配

时间:2013-03-05 19:47:20

标签: c# .net reflection

public class ConflictSaver
{
    private readonly IEnumerable<CommonJobDataInfo> _conflictingJobData;
    private readonly DataAccessDataContext _dc;

    public ConflictSaver(IEnumerable<CommonJobDataInfo> conflictingJobData, DataAccessDataContext dc)
    {
        _conflictingJobData = conflictingJobData;
        _dc = dc;
    }

    public void Save()
    {
        foreach (var data in _conflictingJobData)
        {
            var type = data.ClientBaseObject.GetType();
            var formattedProperty = data.Property.Trim('.').ToUpper();
            foreach (var property in type.GetProperties())
            {
                var currentProperty = data.ClientBaseObject.GetType().GetProperties().First(t => t.Name.Trim() == property.Name.Trim());

                if(currentProperty.Name.ToUpper()== formattedProperty)
                {
                    if (data.UseServerValue)
                        currentProperty.SetValue(currentProperty, data.ServerValue, null);
                    else
                        currentProperty.SetValue(currentProperty, data.ClientValue, null);
                }
            }

        }
    }
}  

当我尝试调用SetValue()时,我在Save()函数中得到对象与目标类型不匹配。我很反思。

1 个答案:

答案 0 :(得分:3)

看起来你正在使用错误的重载并传递错误的对象:

if (data.UseServerValue)
    currentProperty.SetValue(data.ClientBaseObject, data.ServerValue);
else
    currentProperty.SetValue(data.ClientBaseObject, data.ClientValue);

该属性属于data.ClientBaseObject,因此它应该是调用目标。该属性没有idexer,因此if you are on .NET 4.5 or later,您可以完全跳过第三个参数。