简体   繁体   English

实现自定义TypeConverter

[英]Implementing a custom TypeConverter

I have a really simple scenario where I just want to extend the functionality of the System.ComponentModel.BooleanConverter so that it will allow multiple options rather than just true and false . 我有一个非常简单的场景,我只想扩展System.ComponentModel.BooleanConverter的功能,以便它允许多个选项,而不仅仅是truefalse

So for example values like yes , 1 , on etc. are the same as true . 因此,例如yes1on等值与true相同。

I tried overriding the GetStandardValues() methods to do a quick test, my assumption being that if I returned a collection of all my specific values that a call to IsValid(string) should return true if I pass in one of my defined values but this does not appear to be the case. 我尝试重写GetStandardValues()方法来进行快速测试,我的假设是,如果我返回了我所有特定值的集合,那么如果我传入一个我定义的值,那么对IsValid(string)的调用应该返回true似乎并非如此。 Do I have to implement/override a whole bunch of crap to do this? 我是否必须实现/覆盖一大堆废话才能做到这一点?

I'm wondering if it's worth it since all I really need is the IsValid() functionality. 我想知道它是否值得,因为我真正需要的是IsValid()功能。 Or perhaps there is a better option than using TypeDescriptors in the first place? 或者也许首先使用TypeDescriptors有更好的选择?

If you "only need IsValid functionality" then it should be enough to override just it. 如果你“只需要IsValid功能”那么它应该足以覆盖它。 However, in practice CanConvertFrom(Type) is actually the method you should override if you're just looking to test if type can be converted. 但是,实际上CanConvertFrom(Type)实际上是您应该覆盖的方法,如果您只是想测试是否可以转换类型。 This method is used by some infrastructure classes, and just overriding IsValid might not be enough in that case. 某些基础结构类使用此方法,在这种情况下,仅重写IsValid可能还不够。

For boolean converter you should also override ConvertFrom(object) , and just return null if you're not going to use the value. 对于布尔转换器,您还应该重写ConvertFrom(object) ,如果您不打算使用该值,则返回null Otherwise, calling IsValid (which in turn calls CanConvertFrom ) could fail. 否则,调用IsValid (反过来调用CanConvertFrom )可能会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM