TypeConverters:世界上没有足够的TypeDescripter.GetConverter

本文介绍了如何使用TypeDescriptor和TypeConverter类来替代繁琐的类型转换代码,提高代码的可读性和可维护性。通过创建自定义的TypeConverter,可以方便地在不同类型间进行转换,尤其在WinForms、XAML和PowerShell中,这种转换方式更加适用。
摘要由CSDN通过智能技术生成

While reading source today, I saw some code in the wild today that looked roughly like this (not the actual code):

今天在阅读源代码时,我发现今天有些狂野的代码大致像这样(不是实际代码):

type = typeof(T);
if (type == typeof(Boolean))
{
returnValue = (T)((object)Convert.ToBoolean(value));
}
else if (type == typeof(String))
{
returnValue = (T)((object)value);
}
else if (type == typeof(Int16))
{
returnValue = (T)((object)Convert.ToInt16(value));
}
else if (type == typeof(Int32))
{
returnValue = (T)((object)Convert.ToInt32(value));
}
//...and on and on for a dozen+ types

You get the idea. This isn't that uncommon, I've seen it more of than not. The person who is writing it usually knows it's bad 50% of the time, but it's always a trade-off between figuring out the right search query (a tough one, in this case!) and knowing what to look for in MSDN.

你明白了。 这并不少见,我看得更多。 编写它的人通常知道它有50%的时间是很糟糕的,但是在找出正确的搜索查询(在这种情况下,这是一个艰难的查询)和知道要在MSDN中查找的内容之间始终要进行权衡。

This brings up one of my favorite classes in the BCL, the TypeDescriptor class. A method like this:

这在BCL中调出了我最喜欢的类之一,即TypeDescriptor类。 这样的方法:

public static T GetTfromString<T>(string mystring)
{
var foo = TypeDescriptor.GetConverter(typeof(T));
return (T)(foo.ConvertFromInvariantString(mystring));
}

...would allow all that switch/if/else to go away replaced by:

...将允许所有开关/如果/否则消失,替换为:

bool b = GetTfromString
   
   
    
    ("true");
   
   

You'd probably want to expand the method with checks to see if T was in fact, System.Type, or System.String, but you get the idea.

您可能想通过检查来扩展该方法,以查看T实际上是System.Type还是System.String,但是您明白了。

image

There are lots of standard converters like EnumConvertor, ColorConvertor, and more, all waiting for you in System.ComponentModel as seen in the image at right.

有很多标准转换器,例如EnumConvertor,ColorConvertor等,如右图所示,它们都在System.ComponentModel中等待着您。

Not only that, but you can make your own TypeConverters and spread the love. They are used extensively when displaying types in Property Grids, in WinForms, or in XAML. You can also use them in PowerShell as a better way to present your objects as strings when "casting" in PowerShell.

不仅如此,您还可以制作自己的TypeConverters并传播爱心。 在“属性网格”,WinForms或XAML中显示类型时,它们被广泛使用。 您还可以在PowerShell中使用它们,作为在PowerShell中“广播”时以字符串形式显示对象的更好方法

Jesse Liberty has a fine example showing how to use Type Convertors in Silverlight to enable you to put complex types in XAML attributes.

Jesse Liberty有一个很好的示例,展示了如何在Silverlight中使用类型转换器,以使您能够将复杂类型放入XAML属性中

From MSDN:

从MSDN:

To implement a simple type converter that can translate a string to a [Type]

实现一个可以将字符串转换为[Type]的简单类型转换器

  1. Define a class that derives from TypeConverter.

    定义一个从TypeConverter派生的类。

  2. Override the CanConvertFrom method that specifies which type the converter can convert from. This method is overloaded.

    重写CanConvertFrom方法,该方法指定转换器可以转换的类型。 此方法已重载。

  3. Override the ConvertFrom method that implements the conversion. This method is overloaded.

    重写实现转换的ConvertFrom方法。 此方法已重载。

  4. Override the CanConvertTo method that specifies which type the converter can convert to. It is not necessary to override this method for conversion to a string type. This method is overloaded.

    重写CanConvertTo方法,该方法指定转换器可以转换为哪种类型。 不必重写此方法即可转换为字符串类型。 此方法已重载。

  5. Override the ConvertTo method that implements the conversion. This method is overloaded.

    重写实现转换的ConvertTo方法。 此方法已重载。

  6. Override the IsValid method that performs validation. This method is overloaded.

    重写执行验证的IsValid方法。 此方法已重载。

That's it, and when that Type was decorated with an attribute like:

就是这样,当该Type用诸如以下属性装饰时:

[TypeConverter(typeof(MyNewTypeConverter))]

Then that new TypeConverter would be picked up and used by the line of code I showed before. Much better than a switch or pile of if/elses, I think.

然后,新的TypeConverter将被我之前显示的代码行拾取并使用。 我认为,这比开关或一堆if / els好得多。

翻译自: https://www.hanselman.com/blog/typeconverters-theres-not-enough-typedescriptergetconverter-in-the-world

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值