开发者

Set a Nullable value type property via reflection

开发者 https://www.devze.com 2022-12-21 20:45 出处:网络
I\'m attempting to map values of properties (via reflection) between different objects. This appe开发者_JAVA百科ars to be failing oddly on nullable value types. The following code:

I'm attempting to map values of properties (via reflection) between different objects. This appe开发者_JAVA百科ars to be failing oddly on nullable value types. The following code:

 destProperty.SetValue(destObject, sourceProperty.GetValue(sourceObject, null), null);

sets destProperty to null if destProperty is a nullable value type, despite sourceProperty having a value.

Surely this is a fairly common task - I must be missing something simple?


What you posted works for me. Just ran the following. destObject.b is equal to 110 afterwards. notice the final code line is verbatim what you posted.

class Foo {

    public int? a { get; set; }
    public int? b { get; set; }

    static void Main(string[] args) {

        var destObject = new Foo { a = 1, b = 2 };
        var sourceObject = new Foo { a = 110, b = 112 };
        var destProperty = typeof(Foo).GetProperty("b");
        var sourceProperty = typeof(Foo).GetProperty("a");

        destProperty.SetValue(destObject, sourceProperty.GetValue(sourceObject, null), null);
    }
}


Looks good - I get the right value in Destination:

internal class Test
{
    public Test()
    {
        Source = 15;
    }

    public int? Source { get; private set; }
    public int? Destination { get; private set; }
}


var testType = typeof( Test );
var sourceProperty = testType.GetProperty( "Source" );
var destProperty = testType.GetProperty( "Destination" );
var test = new Test();
destProperty.SetValue( test, sourceProperty.GetValue( test, null ), null );


It was something simple - destProperty on this particular class seems to be written to ignore set calls unless certain other properties are set first. I'm pretty sure I wouldn't have been responsible for such a flagrant violation of our coding standards, so I'm going to blame this one on the other guy. Pretty sure.

Thanks to Jimmy & tanascius for confirming it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号