Einzelnen Beitrag anzeigen

Elvis

Registriert seit: 25. Nov 2005
Ort: München
1.909 Beiträge
 
Delphi 2010 Professional
 
#2

AW: Zugriff auf Methode einer generischen Liste

  Alt 5. Mär 2012, 21:30
Hiho,
Wenn du Kontrolle über die generische klasse hast, solltest du dort ein nicht-generisches Interface "implementieren" welches nur diese eine Methode kennt.

Code:
interface ISample
{
  void Fobar();


class MyList<T> : ISample
{
   void Foobar()
  {
      ...
  }
}
Code:
 var miep = 0 new MyList<int>();
object untypedRef = miep;
var mööp = untypedRef as ISample;
if(mööp != null)
  mööp.Foobar();
Wenn du keine Kontrolle über besagte Klasse hast, musst du Reflection nehmen:
Code:
var mi = untypedRef.GetType().GetMethod("Foobar", BindingFlags.Public | BindingFlags.Instance);
mi.DynamicInvoke(untypedRef, null);
Da das ständige Nachslagen Zeit dauert, ist es dann besser, den Call in einem Delegate pro Type abzulegen:
Code:
 static class Miep
{
  static readonly IDictionary<Type, Action<Object>> FoobarCallsByType = new Dictionary<Type, Action<Object>>();

  public static void InvokeFoobar(Object callee)
  {
    var typeRef = callee.GetType();
    lock(FoobarCallsByType)
    {
      Action<Object> foobar;
      if(!FoobarCallsByType.TryGetValue(typeRef, out foobar))
      {
        var mi = typeRef.GetMethod("Foobar", BindingFlags.Public | BindingFlags.Instance);
        FoobarCallsByType.Add(typeRef,
                              foobar = (Action<Object>)Delegate.CreateDelegate(typeof(Action<Object>), mi));
      }
    }
    foobar(callee);
  }
}
Das ist zwar viel langsamer als die erste Variante (ohne Reflection), aber besser als ständig Reflection anzuwerfen ist es auf jeden Fall, gerade wenn man es öfter aufruft...
Robert Giesecke
I’m a great believer in “Occam’s Razor,” the principle which says:
“If you say something complicated, I’ll slit your throat.”
  Mit Zitat antworten Zitat