2013-02-26 109 views
2

在我的代码使用反射像这样得到一个属性的类型:如何将属性从一种类型转换为另一种?

foreach(FilterRule rule in filter.Rules) 
{ 
    PropertyInfo property = typeof(T).GetProperty(rule.Field); 
} 

之后我做几项检查,找出哪些类型实际上,如果类型是long?

else if (property.PropertyType == typeof(long?)) 
{ 
    long dd = Convert.ChangeType(rule.Field, System.Int64); 
} 

我想转换为System.Int64类型。或者更具体到只是long没有可为空,但似乎我没有得到这个,因为rule.FieldString它说第一个参数应该是object,我看到有一些霸主,但没有使用的语法,我正在尝试。

我该如何做这种转换?

回答

2

在你的Convert.ChangeType使用,第二个参数应该是typeof(System.Int64)(在typeof运算符返回的System.Type一个实例),而不是简单地System.Int64

此外,你应该添加一个显式的long(因为ChangeType返回Object):

long dd = (long)Convert.ChangeType(rule.Field, typeof(System.Int64)); 

然而,这似乎是使用Convert.ToInt64 method,而不是一个完美的案例:

long dd = Convert.ToInt64(rule.Field); 
1

如何使用Convert.ToInt64()方法?

将指定值转换为64位有符号整数。

long lfield = Convert.ToInt64(rule.Field); 

var lfield = (long)Convert.ChangeType(rule.Field, typeof(System.Int64)); 

由于thisConvert.ChangeType超载返回object,您可以将其转换为long值。

相关问题