2015-12-05 37 views
2

繼承我有這個接口及其實現泛型參數的類型:獲取從類是從通用接口

public interface IInterface<TParam> 
{ 
    void Execute(TParam param); 
} 

public class Impl : IInterface<int> 
{ 
    public void Execute(int param) 
    { 
     ... 
    } 
} 

如何(這裏INT)獲得TParam使用反射從的typeof類型(默認地將Impl)

+0

刪除';'從'Execute'執行結束。 –

+0

@OrelEraki謝謝) – mtkachenko

回答

2

您可以使用一點反思:

// your type 
var type = typeof(Impl); 
// find specific interface on your type 
var interfaceType = type.GetInterfaces() 
    .Where(x=>x.GetGenericTypeDefinition() == typeof(IInterface<>)) 
    .First(); 
// get generic arguments of your interface 
var genericArguments = interfaceType.GetGenericArguments(); 
// take the first argument 
var firstGenericArgument = genericArguments.First(); 
// print the result (System.Int32) in your case 
Console.WriteLine(firstGenericArgument);