将字符串转换为颜色
我正在通过反射设置字段数据。我在将字符串转换为颜色时遇到问题, 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);
}
}
P.S 颜色值并不总是命名颜色,因此 Color.FromName 不起作用
I'm setting fields data via reflection. And I have a problem to convert string to Color,Convert.ChangeType(stringValue,typeof(Color))
throws Exception. How can i convert to Color in this situation
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);
}
}
P.S Color value is not allways a named Color, so Color.FromName doesnt work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Color 结构具有 TypeConverter 属性,因此您可以执行类似的操作
还有更有用的(在您的情况下)ConvertFromString 方法:
快速浏览一下 Reflector 中的类表明它将按名称或十六进制值解析颜色,这正是您正在寻找的:-)
System.ComponentModel.TypeConverter 框架是比 Convert 类灵活得多
The Color struct has the TypeConverter attribute on it, so you can do something like this
There's also the more useful (in your case) ConvertFromString method:
A quick look at the class in Reflector suggests that it will parse the colors by name or by their hex value, which is what you're looking for :-)
The System.ComponentModel.TypeConverter framework is a lot more flexible that the Convert class
根据 PS 注释,我认为你无法处理这个问题。这些值必须一致,如果它是命名颜色,您可以使用
Color.FromName
,如果它是十六进制值,您可以使用Color.FromArgb
如果不是'如果不一致,您将需要找到一种方法来解析、确定转换,然后完成它。
Based on the PS note, I don't think you are going to be able to handle this. The values have to be consistent, if it is a named color you can use
Color.FromName
, if it is a hex value you can useColor.FromArgb
If it isn't consistent, you are going to need to find a way to parse, determine the conversion, then complete it.