9

これを単純化するクラス(変更できない)があります:

public class Foo<T> {
    public static string MyProperty {
         get {return "Method: " + typeof( T ).ToString(); }
    }
}

しかないときにこのメソッドを呼び出す方法を知りたいSystem.Type

すなわち

Type myType = typeof( string );
string myProp = ???;
Console.WriteLinte( myMethodResult );

私が試したこと:

リフレクションを使用してジェネリック クラスをインスタンス化する方法を知っています。

Type myGenericClass = typeof(Foo<>).MakeGenericType( 
    new Type[] { typeof(string) }
);
object o = Activator.CreateInstance( myGenericClass );

しかし、静的プロパティを使用しているので、これはクラスをインスタンス化するのに適していますか? コンパイル時にキャストできない場合、メソッドにアクセスするにはどうすればよいですか? (System.Object には の定義がありませんstatic MyProperty)

編集 投稿後に気づ​​いたのですが、使用しているクラスはメソッドではなくプロパティです。混乱をお詫び申し上げます

4

4 に答える 4

6

メソッドは静的であるため、オブジェクトのインスタンスは必要ありません。直接呼び出すことができます:

public class Foo<T>
{
    public static string MyMethod()
    {
        return "Method: " + typeof(T).ToString();
    }
}

class Program
{
    static void Main()
    {
        Type myType = typeof(string);
        var fooType = typeof(Foo<>).MakeGenericType(myType);
        var myMethod = fooType.GetMethod("MyMethod", BindingFlags.Static | BindingFlags.Public);
        var result = (string)myMethod.Invoke(null, null);
        Console.WriteLine(result);
    }
}
于 2012-07-09T14:10:37.550 に答える
3

まあ、静的メソッドを呼び出すためにインスタンスは必要ありません。

Type myGenericClass = typeof(Foo<>).MakeGenericType( 
    new Type[] { typeof(string) }
);

大丈夫です...では、単に:

var property = myGenericClass.GetProperty("MyProperty").GetGetMethod().Invoke(null, new object[0]);

するべきです。

于 2012-07-09T14:12:24.033 に答える
3
typeof(Foo<>)
    .MakeGenericType(typeof(string))
    .GetProperty("MyProperty")
    .GetValue(null, null);
于 2012-07-09T14:13:57.330 に答える
2

次のようなものが必要です。

typeof(Foo<string>)
    .GetProperty("MyProperty")
    .GetGetMethod()
    .Invoke(null, new object[0]);
于 2012-07-09T14:09:37.727 に答える