興味のある仲間のために、私はたくさん検索して、ジェネリックとリフレクションを使用した解決策を思いつきました:
public static class MyConvertingClass
{
public static T Convert<T>(APIElement element)
{
System.Type type = typeof(T);
if (conversions.ContainsKey(type))
return (T)conversions[type](element);
else
throw new FormatException();
}
private static readonly Dictionary<System.Type, Func<Element, object>> conversions = new Dictionary<Type,Func<Element,object>>
{
{ typeof(bool), n => n.GetValueAsBool() },
{ typeof(char), n => n.GetValueAsChar() },
{ typeof(DateTime), n => n.GetValueAsDatetime() },
{ typeof(float), n => n.GetValueAsFloat32() },
{ typeof(double), n => n.GetValueAsFloat64() },
{ typeof(int), n => n.GetValueAsInt32() },
{ typeof(long), n => n.GetValueAsInt64() },
{ typeof(string), n => n.GetValueAsString() }
};
}
public static main()
{
// Defined by the user:
Type fieldType = typeof(double);
// Using reflection:
MethodInfo method = typeof(MyConvertingClass).GetMethod("Convert");
method = method.MakeGenericMethod(fieldType);
Console.WriteLine(method.Invoke(null, new object[] { fieldData }));
}