本文介绍了设置属性Nullable<<>通过反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试动态设置Nullable<>属性。

I try to set a Nullable<> property dynamicly.

我获得我的财产ex:

I Get my property ex :

PropertyInfo property = class.GetProperty("PropertyName"); // My property is Nullable<> at this time So the type could be a string or int

我想通过反射设置我的属性

I want to set my property by reflection like

property.SetValue(class,"1256",null);

当我的属性是Nullable<> Generic时,它不工作。所以我尝试找到一种方法来设置我的财产。

It's not working when my property is a Nullable<> Generic. So i try to find a way to set my property.

要知道我执行的可空<>属性的类型

To know the type of my nullable<> property i execute

Nullable.GetUnderlyingType(property.PropertyType)

任何想法?


  • 我尝试用

  • I Try to create an instance of my Nullable<> property with

var nullVar = Activator.CreateInstance(typeof(Nullable<>)。MakeGenericType(new Type [] {Nullable.GetUnderlyingType(property.PropertyType)}));

var nullVar = Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(new Type[] { Nullable.GetUnderlyingType(property.PropertyType) }));

但是nullVar总是为空

But nullVar is always Null

推荐答案

如果你想将任意一个字符串转换为Nullable的基础类型,可以使用Convert类:

If you want to convert an arbitrary string to the underlying type of the Nullable, you can use the Convert class:

var propertyInfo = typeof(Foo).GetProperty("Bar");
object convertedValue = null;
try
{
    convertedValue = System.Convert.ChangeType("1256",
        Nullable.GetUnderlyingType(propertyInfo.PropertyType));
}
catch (InvalidCastException)
{
    // the input string could not be converted to the target type - abort
    return;
}
propertyInfo.SetValue(fooInstance, convertedValue, null);

如果目标类型为int,short,long(或无符号变体,输入字符串表示一个非负数),double,float或decimal。警告:这不是快速代码。

This example will work if the target type is int, short, long (or unsigned variants, since the input string represents a non-negative number), double, float, or decimal. Caveat: this is not fast code.

这篇关于设置属性Nullable&lt;&lt;&gt;通过反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:18