The technique that I've used in the past for this is to have a dictionary of delegates for each type. Then I define a static variable to hold them - or use DI to inject them.
private static Dictionary<Type, Delegate> _parsers = new Dictionary<Type,
Delegate>()
{
{ typeof(int), (Func<string, int>)(t => int.Parse(t)) },
{ typeof(double), (Func<string, double>)(t => double.Parse(t)) },
};
To retrieve the value from the text you just do this:
public void FromText(string rawValue)
{
value = ((Func<string, T>)_parsers[typeof(T)]).Invoke(rawValue);
}
The type casting rules for delegates are more relaxed and make this work like a
treat.
From: [email protected] [mailto:[email protected]] On
Behalf Of Greg Keogh
Sent: Saturday, 4 June 2011 14:28
To: 'ozDotNet'
Subject: RE: Generic class question
Surely there's very few types that a) you're using, that b) offer that Parse
method. Could you save the reflection call and simply do something like
if (typeof(T) is decimal) { decimal.Parse(...); }
elseif (typeof(T) is int) { int.Parse(...); }
I can't cast a double, int or long to the generic type T which is constrained
to be a struct. Hmmm .. why?
[cid:[email protected]]
As David says, if I'm doing if typeof(X) in the class then there's no point in
it being generic.
The class I'm using is in fact a wrapper around a two-dimensional array of the
T (a matrix of T). It just seemed natural to have a generic class to hold the
matrix of T values, and it was working lovely until I stumbled upon this
brain-teaser of parsing a string to set one of the T values.
Greg
<<inline: image001.png>>
