2011-02-18 120 views
1

我正在通过反射设置字段数据。我有一个问题,将字符串转换为颜色, Convert.ChangeType(stringValue,typeof(Color))抛出异常。我怎么能转换成颜色在这种情况下将字符串转换为颜色

 PropertyInfo[] propertis = typeof(TEntity).GetProperties(); 
     foreach (var attribute in element.Attributes()) 
     { 
      var property = propertis.Where(x => x.Name == attribute.Name).FirstOrDefault(); 
      if (property != null) 
      { 
       property.SetValue(someVariable, Convert.ChangeType(attribute.Value,property.PropertyType), null); 
      } 
     } 

PS颜色值不ALLWAYS一个名为Color,所以Color.FromName不起作用

+3

这不是一种命名的颜色,你想要将它转换为“Color”究竟是怎样的? – mquander 2011-02-18 15:45:36

+2

没有例子,字符串可以包含什么值无法回答 – BrokenGlass 2011-02-18 15:49:49

回答

3

颜色结构有的TypeConverter属性就可以了,所以你可以做这样的事情

var converter=TypeDescriptor.GetConverter(property.PropertyType); 
object convertedValue=converter.ConvertTo(attribute.Value, property.PropertyType); 
property.SetValue(someVariable, convertedValue, null); 

还有更多有用的(你的情况)ConvertFromString方法:

var converter=TypeDescriptor.GetConverter(property.PropertyType); 
object convertedValue=converter.ConvertFromString(attribute.Value); 
property.SetValue(someVariable, convertedValue, null); 

就让我们来看看在反射器类表明,它会通过名称或它们的十六进制值,这是你在找什么:-)

系统解析颜色.ComponentModel.TypeConverter框架是很多更灵活的转换类基础上PS注

1

,我不认为你将能够处理这个问题。值必须一致,如果它是可以使用的指定颜色Color.FromName,如果它是可以使用的十六进制值Color.FromArgb

如果不一致,则需要找到解析方法,确定转换,然后完成它。