2010-08-02 19 views
28

का उपयोग करके एक स्थिर विधि को कॉल करना Type से मैं एक स्थैतिक विधि कैसे कॉल करूं, मान लीजिए कि मुझे Type चर और स्थिर विधि का नाम पता है?टाइप

public class FooClass { 
    public static FooMethod() { 
     //do something 
    } 
} 

public class BarClass { 
    public void BarMethod(Type t) { 
     FooClass.FooMethod()   //works fine 
     if (t is FooClass) { 
      t.FooMethod();   //should call FooClass.FooMethod(); compile error 
     } 
    } 
} 

तो, एक Type t दिया, उद्देश्य वर्ग Type t की है उस पर FooMethod() कॉल करने के लिए है। असल में मुझे typeof() ऑपरेटर को उलट करने की आवश्यकता है। ऊपर के उदाहरण आप के रूप में अच्छी FooClass.FooMethod कॉल कर सकते हैं के रूप में वहाँ उस के लिए प्रतिबिंब का उपयोग कर कोई मतलब नहीं है में

public class BarClass { 
    public void BarMethod(Type t) { 
     FooClass.FooMethod()   //works fine 
     if (t == typeof(FooClass)) { 
      t.GetMethod("FooMethod").Invoke(null, null); //null - means calling static method 
     } 
    } 
} 
बेशक

:

उत्तर

39

आप MethodInfo.Invoke विधि कॉल करने की जरूरत है। MethodInfo वर्ग में

public class BarClass { 
    public void BarMethod(Type t, string method) { 
     var methodInfo = t.GetMethod(method); 
     if (methodInfo != null) { 
      methodInfo.Invoke(null, null); //null - means calling static method 
     } 
    } 
} 

public class Foo1Class { 
    static public Foo1Method(){} 
} 
public class Foo2Class { 
    static public Foo2Method(){} 
} 

//Usage 
new BarClass().BarMethod(typeof(Foo1Class), "Foo1Method"); 
new BarClass().BarMethod(typeof(Foo2Class), "Foo2Method");  
+0

धन्यवाद इगोर, यह ठीक काम करेगा (हालांकि मैं सी # में निराश हूं - यह पूरी तरह से गैर-प्रकार का दिखता है) मेरे वास्तविक कोड में टाइप वेरिएबल में कई कक्षाएं हो सकती हैं, इसलिए प्रतिबिंब आवश्यक है। – MrEff

2

चेक और प्रकार पर GetMethod() तरीके: निम्न नमूना अधिक समझ में आता है।

विभिन्न स्थितियों के लिए कई अलग-अलग ओवरलोड हैं।

संबंधित मुद्दे