通过反射设置Nullable值类型属性

时间:2010-03-05 09:02:39

标签: c# reflection nullable

我正在尝试在不同对象之间映射属性值(通过反射)。这似乎在可空值的类型上奇怪地失败了。以下代码:

 destProperty.SetValue(destObject, sourceProperty.GetValue(sourceObject, null), null);
如果destProperty是可以为空的值类型,

将destProperty设置为null,尽管sourceProperty具有值。

当然,这是一项相当普遍的任务 - 我一定会错过一些简单的事情吗?

3 个答案:

答案 0 :(得分:1)

你发布的内容对我有用。刚刚运行以下内容。之后destObject.b等于110。请注意最终的代码行是逐字记录的。

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);
    }
}

答案 1 :(得分:1)

看起来不错 - 我在目的地中获得正确的值:

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 );

答案 2 :(得分:0)

这很简单 - 除非先设置某些其他属性,否则写入此特定类的destProperty似乎会忽略set调用。我非常肯定我不会对这种公然违反我们的编码标准负责,所以我要把这个归咎于另一个人。很确定。

感谢Jimmy& tanascius确认它应该工作。

相关问题