سؤال

I'm looking for the best way to implement a method that behave differenty according to a type argument (I can't use dynamic here).

public class Methods
{
    public int someMethod1() { return 1; }
    public string someMethod2() { return "2"; }

    public ??? process(System.Type arg1) ???
    {
        if (arg1 is of type int) ??
            return someMethod1();
        else if (arg1 is of type string) ??
            return someMethod2();
    }
}

If my example is not clear, here is my real need :
- The user of my lib can specify what return type he wants from his request,
- Depending on the type asked, i have to use a different set of methods (like GetValueAsInt32() or GetValueAsString())

Many thanks !!

هل كانت مفيدة؟

المحلول 2

For interested buddies, I've searched around a lot and I've come up with a solution using generics and reflection:

  • The converting generic method:
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() }
    };
}
  • The main method:
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 }));
}

نصائح أخرى

What if you just use Generic to allow consumers to determine the return type:

public T process<T>(Type arg1) {...}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top