1

あるオブジェクトから別のオブジェクトにプロパティをコピーするためのクラスを作成しましたが、例外が発生しました:System.Reflection.TargetException:オブジェクトがターゲットタイプと一致しません。fromPropValueが正しいタイプであり、nullではないことなどを確認しました。もちろん、recepientのプロパティはBinaryです。

public class Reflector
{
    public void ReflectProperties(object from, object to) 
    { 
        Type toType = to.GetType();
        Type fromType = from.GetType();
        var toProperties = toType.GetProperties();

        foreach (var prop in toProperties)
        {
            var fromProp = fromType.GetProperty(prop.Name);

            if (fromProp != null)
            {
                var propType = prop.PropertyType;
                var fromPropValue = fromProp.GetValue(from, null);

                if (propType == typeof(Binary))
                    prop.SetValue(this, (Binary)fromPropValue, null); // <-- error
                else if (propType == typeof(string))
                    prop.SetValue(this, (string)fromPropValue, null);
                else if (propType == typeof(bool))
                    prop.SetValue(this, (bool)fromPropValue, null);
            }
        }
    }
}

PS:オブジェクトfromはオブジェクトtoの親であり、すべてのプロパティの値を親から子にコピーしたいだけです。

4

1 に答える 1

2

prop.SetValue(to, ...の代わりに欲しいと思いますprop.SetValue(this, ...

ifまた、ステートメントやキャストは必要ありません。あなたはただすることができますprop.SetValue(to, fromPropValue, null);

于 2012-10-29T11:48:46.880 に答える