2011-12-07 9 views
1

パラメータと戻り値なしでReflection経由でメソッドを呼び出す方法はありますか?ここでパラメータと戻り値なしでReflection経由でメソッドを呼び出す方法はありますか?

は、typeof演算(???)内でなければならない何MSDN sample

// Define a class with a generic method. 
public class Example 
{ 
    public static void Generic<T>() 
    { 
     Console.WriteLine("\r\nHere it is: {0}", "DONE"); 
    } 
} 

のですか?

MethodInfo miConstructed = mi.MakeGenericMethod(typeof(???)); 

ありがとうございます!

+0

をおそらく、いずれかのタイプが動作します。文字列を使ってみましたか? – stuartd

+0

これをチェックしてください:http://stackoverflow.com/questions/569249/methodinfo-invoke-with-out-parameter –

+0

はい、私はしました。それは動作しません。 –

答えて

3

を使用すると、C#の通過ことを呼び出すされた場合は、たとえば、種類を供給する必要があります:印刷する必要があります

public class Example 
{ 
    public static void Generic<T>() 
    { 
     Console.WriteLine("The type of T is: {0}", typeof(T)); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     var mi = typeof(Example).GetMethod("Generic"); 
     MethodInfo miConstructed = mi.MakeGenericMethod(typeof(string)); 
     miConstructed.Invoke(null, null); 
    } 
} 

:だからあなたは、一般的な引数として使用したい型を渡します:

Example.Generic<int>(); 

この要件は変更されません。単純に、その行はなる:完全に、作業説明のため

mi.MakeGenericMethod(typeof(int)).Invoke(null, null); 

class Example 
{ 
    public static void Generic<T>() 
    { 
     System.Console.WriteLine("\r\nHere it is: {0}", "DONE"); 
    } 
    static void Main() 
    { 
     var mi = typeof (Example).GetMethod("Generic"); 
     mi.MakeGenericMethod(typeof(int)).Invoke(null, null); 
    } 
} 
3

ジェネリックメソッドを呼び出す前に、その汎用引数を指定する必要があります。

The type of T is: System.String 
関連する問題