Đã sử dụng phương thức Sao chép với mã này ở các vị trí khác nhau trong các dự án trước đó (để xử lý các đối tượng có cùng thuộc tính được đặt tên nhưng không lấy được lớp cơ sở hoặc triển khai một giao diện chung).SetValue trên lỗi thể hiện của PropertyInfo "Đối tượng không khớp với loại mục tiêu" C#
nơi mới làm việc, codebase mới - bây giờ nó không ở SetValue với "đối tượng không phù hợp với loại mục tiêu" ngay cả những ví dụ trên rất đơn giản ... và nó làm việc trong tuần trước ....
public static void Copy(object fromObj, object toObj)
{
Type fromObjectType = fromObj.GetType();
Type toObjectType = toObj.GetType();
foreach (System.Reflection.PropertyInfo fromProperty in
fromObjectType.GetProperties())
{
if (fromProperty.CanRead)
{
string propertyName = fromProperty.Name;
Type propertyType = fromProperty.PropertyType;
System.Reflection.PropertyInfo toProperty =
toObjectType.GetProperty(propertyName);
Type toPropertyType = toProperty.PropertyType;
if (toProperty != null && toProperty.CanWrite)
{
object fromValue = fromProperty.GetValue(fromObj,null);
toProperty.SetValue(toProperty,fromValue,null);
}
}
}
}
private class test
{
private int val;
private string desc;
public int Val { get { return val; } set { val = value; } }
public string Desc { get { return desc; } set { desc = value; } }
}
private void TestIt()
{
test testo = new test();
testo.Val = 2;
testo.Desc = "TWO";
test g = new test();
Copy(testo,g);
}
Hy vọng rằng ai đó có thể chỉ ra nơi tôi đang bị điên?
D'oh! đó là lỗi tôi đã sửa thời gian LAST tôi đã viết - và quên kiểm tra lần này ... – kpollock