Reputation: 873
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?
Upvotes: 4
Views: 177
Reputation: 16543
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 (i.e. int[], long[], etc), which has the benefit of ensuring that the cast will not throw an exception.
Upvotes: 1
Reputation: 11
As @nawfal mentioned you could use ITest as Generic:
public interface ITest<T>
{
T MyMethod(params object[] args);
}
Upvotes: 1
Reputation: 73492
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
Upvotes: 1