首页 新闻 会员 周边

C#类型转换(反射)

0
悬赏园豆:10 [已解决问题] 解决于 2013-08-16 09:06

如何将一个对象转换为指定Type类型?? 我这有个方法。如果是普通的对象,并且有默认的无参数构造函数,转换目前没发现问题。但如果是集合(比如数组,List<T>)转换不了。。
这个方法是用来反射调用方法的,而参数是反序列化JSON得来的。。
比如我有个方法:

public void Test(int[] numbers) // 这个可能不是int[],可能是任意类型,但是我能够得到他的Type实例
{
}

我要反射调用这个方法。参数是由客户端以Json格式发送过来的。

Stream stream = this.Request.InputStream;
Encoding encoding = this.Request.ContentEncoding;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
string postData = encoding.GetString(bytes);
JavaScriptSerializer serializer = new JavaScriptSerializer();
object arg = serializer.DeserializeObject(postData);
object[] numbers = arg as object[]// 获取参数,虽然是object数组,但是元素都是int的。


但是得到的是object数组。

参数的Type我用其他的方式能够获取。。

Type type = typeof(int[]);// 这个Type并不是这样获取的,由于比较麻烦,这里为了容易说清楚,直接写死

现在我要调用最下面那个ConvertObject方法来把object[] 转换为 int[]

object o = this.ConvertObject(numbers,type); // 这个numbers是通过JSON获取到的参数

 

其实为了说清楚,说了一堆废话,只要看到下面这个方法,就知道我想干什么了。。。

 1 /// <summary>
 2 /// 将一个对象转换为指定类型
 3 /// </summary>
 4 /// <param name="obj">待转换的对象</param>
 5 /// <param name="type">目标类型</param>
 6 /// <returns>转换后的对象</returns>
 7 private object ConvertObject(object obj, Type type)
 8 {
 9     if (type == null) return obj;
10     if (obj == null) return type.IsValueType ? Activator.CreateInstance(type) : null;
11  
12     Type underlyingType = Nullable.GetUnderlyingType(type);
13     if (type.IsAssignableFrom(obj.GetType())) // 如果待转换对象的类型与目标类型兼容,则无需转换
14     {
15         return obj;
16     }
17     else if ((underlyingType ?? type).IsEnum) // 如果待转换的对象的基类型为枚举
18     {
19         if (underlyingType != null && string.IsNullOrEmpty(obj.ToString())) // 如果目标类型为可空枚举,并且待转换对象为null 则直接返回null值
20         {
21             return null;
22         }
23         else
24         {
25             return Enum.Parse(underlyingType ?? type, obj.ToString());
26         }
27     }
28     else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type)) // 如果目标类型的基类型实现了IConvertible,则直接转换
29     {
30         try
31         {
32             return Convert.ChangeType(obj, underlyingType ?? type, null);
33         }
34         catch
35         {
36             return underlyingType == null ? Activator.CreateInstance(type) : null;
37         }
38     }
39     else
40     {
41         TypeConverter converter = TypeDescriptor.GetConverter(type);
42         if (converter.CanConvertFrom(obj.GetType()))
43         {
44             return converter.ConvertFrom(obj);
45         }
46         ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
47         if (constructor != null)
48         {
49             object o = constructor.Invoke(null);
50             PropertyInfo[] propertys = type.GetProperties();
51             Type oldType = obj.GetType();
52             foreach (PropertyInfo property in propertys)
53             {
54                 PropertyInfo p = oldType.GetProperty(property.Name);
55                 if (property.CanWrite && p != null && p.CanRead)
56                 {
57                     property.SetValue(o, ConvertObject(p.GetValue(obj, null), property.PropertyType), null);
58                 }
59             }
60             return o;
61         }
62     }
63     return obj;
64 }
ConvertObject

 

俗人...的主页 俗人... | 初学一级 | 园豆:83
提问于:2013-08-12 14:54
< >
分享
最佳答案
0

为什么不直接用Json.NET搞定

收获园豆:10
dudu | 高人七级 |园豆:30994 | 2013-08-12 16:40

嗯,我试试。。

俗人... | 园豆:83 (初学一级) | 2013-08-12 17:07
其他回答(1)
0

可以序列化成 特定类型,然后再反序列化成你想要的类型,不知道是不是你想要的

代码:可以搜索序列化和反序列化,代码很少

风醉 | 园豆:1197 (小虾三级) | 2013-08-12 15:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册