使用反射设置Int32的值

Mic*_*tum 5 .net c# reflection

我想使用反射根据文件中的数据设置一些字段.我可以拥有的信息是TypeName,TypeValue和FieldName.

虽然这对类(Activator.CreateInstance和PropertyInfo.SetValue)来说是微不足道的,但是对于像Int32这样没有任何属性的值类型,我有点愚蠢.我看到IsValueType在那些类型上是真的,但由于我的TypeValue是一个字符串(即字符串TypeValue ="400"),我不知道如何分配它.

我是否必须GetMethods()用来检查是否有.Parse方法?这是为了TypeConverter什么?

我知道我可以硬编码一些常见的值类型(反正没有那么多)并且有一个很大的switch()语句,但是我想知道是否有一些东西可以自动执行"Convert String to T"转换?

Ars*_*yan 7

// get the type converters we need
TypeConverter myConverter = TypeDescriptor.GetConverter(typeof(int));

// get the degrees, minutes and seconds value
int Degrees = (int)myConverter.ConvertFromString(strVal);
Run Code Online (Sandbox Code Playgroud)

这应该有所帮助