将基本类型和字符串的限制通用扩展方法 [英] Constrain generic extension method to base types and string
问题描述
我想要一个XElement / XAttribute的扩展方法,允许我应用一个ValueOrDefault逻辑 - 也许与各种略有不同的实现:ValueOrNull,ValueOrDefault,NumericValueOrDefault(它验证如果值是数字),但我想约束这些方法,使它们只能使用ValueTypes或String(即使用任何其他引用类型没有任何意义。是否可以通过每个方法的一个实现来做到这一点,或者我必须有一个约束是Structure,其中约束是String - 如果我在通用约束中结合Structure和String,我得到错误:
'Structure'约束和特定类类型约束不能组合。
I want to have an extension method for XElement/XAttribute that allows me to apply a "ValueOrDefault" logic - perhaps with various slightly different implementations: ValueOrNull, ValueOrDefault, NumericValueOrDefault (which validates if the value is numeric), but I want to constrain these methods so that they can only work with ValueTypes or String (i.e. it does not really make sense to use any other reference types. Is it possible to do this with one implementation of each method, or will I have to have one where the constraint is "Structure" and one where the constraint is "String" - if I combine Structure and String in the generic constraint, I get the error : 'Structure' constraint and a specific class type constraint cannot be combined.
当前方法实现的示例如下:
An example of the current method implementation is as follows:
<Extension()> _
Public Function ValueOrDefault(Of T As {Structure})(ByVal xe As XElement, ByVal defaultValue As T) As T
If xe Is Nothing or xe.Value = "" Then
Return defaultValue
End If
Return CType(Convert.ChangeType(xe.Value, GetType(T)), T)
End Function
推荐答案
不,没有办法在类型约束。
No, there's no way of doing an "or" in type constraints.
在我看来,你真的想要一个重载,它是一个值类型约束的泛型,一个是nongeneric但是有一个字符串参数。你实际上不能指定一个密封类的类型约束。
It seems to me that you really want one overload which is generic with a value type constraint, and one which is nongeneric but has a string parameter. You can't actually specify a type constraint of a sealed class anyway.
这篇关于将基本类型和字符串的限制通用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!