简体   繁体   中英

Use Generic Method With Type DataType

This is ITest Interface:

public interface ITest
{
    Type ReturnType { get; }

    Object MyMethod(params object[] args);

}

And Test Class:

public class Test: ITest
{
    public Type ReturnType { get { return typeof(long); } }

    public Object MyMethod(params object[] args)
    {
        long sum = 0;
        foreach(object arg in args)
        {
          sum += (long)arg;
        }
        return sum;
    }
}

So I need a method that convert automatically result of ITest Method with ReturnType Type.

I Think Something like This:

public T Transform<T>(Type T, object result)
{
   return (T)result;
}

And Use Like This:

Test test = new Test();
long result = Transform(test.ReturnType, test.MyMethod(1,2,3,4));

But as You Know I can't Use generic Method Like This, I don't want to declare return Type Explicitly like this:

long result = Transform<long>(test.MyMethod(1,2,3,4));

any suggestion?

Exactly what you're asking is not possible without reflection.

You can mark ITest as Generic and henceforth everything becomes easy.

public interface ITest<T>
{
    Type ReturnType { get; }//redundatnt

    T MyMethod(params object[] args);
}


public class Test : ITest<long>
{
    public Type ReturnType { get { return typeof(long); } }//redundatnt

    public long MyMethod(params object[] args)
    {
        long sum = 0;
        foreach (object arg in args)
        {
            long arg1 = Convert.ToInt64(arg);
            sum += arg1;
        }
        return sum;
    }
}

Test test = new Test();
long result = test.MyMethod(1,2,3,4);//No transform nothing, everything is clear

Reflection is required, but the important thing is that this approach is highly questionable as well as not 100% possible as you cannot cast an object to a long . Try running the below:

    static void Main()
    {
        int i = 1;
        object o = i;
        long l = (long)o;
    }

As Sriram demonstrated, it is possible to implement type specific methods, but I assume this would defeat the purpose of your question/design. It would also be easier to simply have overloaded methods w/ different parameter types (ie int[], long[], etc), which has the benefit of ensuring that the cast will not throw an exception.

As @nawfal mentioned you could use ITest as Generic:

public interface ITest<T>
{

    T MyMethod(params object[] args);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM