亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C#類型轉換(反射)

C#類型轉換(反射)

開滿天機 2018-12-07 07:49:41
如何將一個對象轉換為指定Type類型???我這有個方法。如果是普通的對象,并且有默認的無參數構造函數,轉換目前沒發現問題。但如果是集合(比如數組,List)轉換不了。。這個方法是用來反射調用方法的,而參數是反序列化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 /// 2 /// 將一個對象轉換為指定類型 3 /// 4 /// 待轉換的對象 5 /// 目標類型 6 /// 轉換后的對象 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 ?
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

可以序列化成 特定類型,然后再反序列化成你想要的類型,不知道是不是你想要的 代碼:可以搜索序列化和反序列化,代碼很少
查看完整回答
反對 回復 2018-12-09
  • 2 回答
  • 0 關注
  • 861 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號