This question already has an answer here:
I am having the following type where T
should only be of int
, double
, string
and datetime
. However using a constraint on class
would be too broad.
public class Field<T> where T : class
{
public int Tag { get; set; }
public T Value { get; set; }
}
Possible solutions that come to my mind:
- Add a constructor that does a check (
if ((typeof(T) != typeof(string)) ...
) - Change the class to be abstract and move
Value
to the concrete implementing class. This however would result in having several additional types, likeStringField : Field
,DateTimeField : Field
, etc.
Also I would like to be more specific about the Tag
property and replace it with an enum, which ensures that only values of predefined range can be used. This approach however would result in a (tiny) overhead, as I need to instance representation of Field
as a string.
What would be the best model to choose? Anything I am missing? Thanks in advance
Aucun commentaire:
Enregistrer un commentaire