lundi 13 juillet 2015

I need something like Add(object arg0, object arg1)

I have a baseclass MyBaseClass that has two methods:

public abstract class Baseclass
{
    public abstract Type GetProvidedType();
    public abstract object GetProvidedData();
}

There are some implementations of that baseclass, and they all provide completely different data. Some may provide an int, some may provide a Vector2, or some complex type. I can't say what at compile time.

What I would like to do, is adding the returns of two different GetProvidedData() calls. Something like:

MyBaseClass provider0 = GetProvider(0);
MyBaseClass provider1 = GetProvider(1);
return provider0.GetProvidedData() + provider1.GetProvidedData();

That, of course, leads to error CS0019: Operator '+' cannot be applied to operands of type 'object' and 'object'.

  • I tried using the dynamic keyword. But that's not implemented enough yet in Unity (I'm using 5.1.1f1).
  • I tried using reflection. Like making GetProvidedData() a generic method, getting the MethodInfo via reflection, using MakeGenericMethod, and calling that. Which of course, when invoked, provides me with an effing object again.
  • Even Convert.ChangeType returns an object. Which, at that point, is useless to me.
  • I tried getting the + operator via reflection (it's a method with the name "op_Addition"), but that won't work for native types like int.

Any ideas how to tackle this?





Aucun commentaire:

Enregistrer un commentaire