关于类型转换,动态类型转换

MOmo400 2009-04-08 09:07:12
有数据A,可以取得到其类型.PropertyType是A的类型.
现在有一数据B string型,要把B的值赋给A,类型之间怎么转换
我一开始的时候这么做:

B="10"; //或者其它值

PropertyInfo pt = type.GetProperty(A, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

Type type=pt.PropertyType;//这里是A的类型

pt.SetValue(pro, (Object)B, null); //这里进行赋值

但如果A是其它类型的时候,比如Int 的时候就会出错.请问如何把B转换为相应要求的类型
...全文
99 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
MOmo400 2009-04-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gomoku 的回复:]
"相应要求的类型"要有从string转化到该类型的TypeConverter。
比如PointConvert的作用就是就容许从(3,4)字符串到一个Point的转换:

[TypeConverter(typeof(PointConverter))]
public struct Point
{
...
}
[/Quote]

不太明白
gomoku 2009-04-08
  • 打赏
  • 举报
回复
"相应要求的类型"要有从string转化到该类型的TypeConverter。
比如PointConvert的作用就是就容许从(3,4)字符串到一个Point的转换:

[TypeConverter(typeof(PointConverter))]
public struct Point
{
...
}
bulong0721 2009-04-08
  • 打赏
  • 举报
回复
类型转换方式:

// 隐式转换
public static implicit operator AType(BType b)
{
...
}
BType b = ...
AType a = b;

// 显式转换
public static explicit operator AType(BType b)
{
...
}
BType b = ...
AType (BType)a = b;

// Convert.ChangeType
Double d = -2.345;
int i = (int)Convert.ChangeType(d, typeof(int));

// TypeConverter
Color c = Color.Red;
Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧