Constrain generic extension method to base types a

2019-07-19 20:33发布

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

1条回答
萌系小妹纸
2楼-- · 2019-07-19 21:33

No, there's no way of doing an "or" in type constraints.

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.

查看更多
登录 后发表回答