- using System;
- public partial class User_Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- MemberInfo infoMember = new MemberInfo();
- System.Reflection.PropertyInfo p = infoMember.GetType().GetProperty("ID");
- p.SetValue(infoMember, Convert.ChangeType("7", p.PropertyType), null);
- }
- }
- public class MemberInfo
- {
- Int32 _ID;
- public Int32 ID
- {
- get { return _ID; }
- set { _ID = value; }
- }
- }
以上成功,但当将int改为int?时
- using System;
- public partial class User_Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- MemberInfo infoMember = new MemberInfo();
- System.Reflection.PropertyInfo p = infoMember.GetType().GetProperty("ID");
- p.SetValue(infoMember, Convert.ChangeType("7", p.PropertyType), null);
- }
- }
- public class MemberInfo
- {
- Int32? _ID;
- public Int32? ID
- {
- get { return _ID; }
- set { _ID = value; }
- }
- }
报错:
从“System.String”到
“System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”
的强制转换无效。解决方法:
定义ConvertTo扩展方法,我们就可以进行任意的类型转化了——不论目标类型是可空值类型,还是非可空值类型
public static class ConvertionExtensions
{
public static T ConvertTo
(this IConvertible convertibleValue)
{
if (string.IsNullOrEmpty(convertibleValue.ToString()))
{
return default(T);
}
if (!typeof(T).IsGenericType)
{
return (T)Convert.ChangeType(convertibleValue, typeof(T));
}
else
{
Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
}
}
throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".", convertibleValue.GetType().FullName, typeof(T).FullName));
}
}
p.SetValue(infoMember, Convert.ChangeType("7", p.PropertyType), null);
将上面这句话改成下面这句:
p.SetValue(infoMember, "7".ConvertTo>(), null);
阅读(7663) | 评论(0) | 转发(0) |