Constraint which force generic parameter to be parseable from string
In this topic one can find solution to make generic class which provides parsing from string to generic parameter type. However, it could happen that type given to this parameter does not provide such conversion. Is there a way to make constraint assuring that?
UPDATE: Thank you for your answers. However I know I can generally make constraints. T开发者_运维知识库he problem is: is there any interface that all types, which Convert.ChangeType won't fail at, implements. Or which is implemented by all types with Parse(string) method.
Since, as I said in my comment, you can't add interfaces to specific types nor can you use duck-typing in generic type constraints, you'll probably have to end up writing a bit of a hacky solution. I think your best bet is to make several overloads of your parsing function, one for each of the basic types (int, char, string, etc.) and then provide a generic one that has IConvertible as its generic constraint. The compiler will choose the right overload, or none at all in the case of non-convertible types.
You need to use Type Constraints to restrict what types of objects can be used in the generic class. You should define an interface that can be used to do that conversion and than set that interface as the constraint.
精彩评论