簡體   English   中英

通過反射在類上調用多個通用接口方法

[英]Invoke multiple generic interface methods on a class through reflection

警告: 雖然接受的答案是正確的,但對於任何試圖實現此問題的人,請參閱@ CodesInChaos的評論。 這對我來說是一個壞主意。


我有一個通用接口和一個實現接口'n'次數的類:

interface IA<T>
{
    T Foo();
}

class Baz1 { }
class Baz2 { }

class Bar : IA<Baz1>, IA<Baz2>
{
    Baz1 Foo() { return new Baz1(); }
    Baz2 Foo() { return new Baz2(); }
}

如何使用反射在Bar實例上調用兩個Foo方法?

我已經有以下代碼來獲取接口定義和泛型類型參數:

class Frobber
{
    void Frob(object frobbee)
    {
        var interfaces = frobbee.GetType()
            .GetInterfaces()
            .Where(i => i.IsGenericType &&
                i.GetGenericTypeDefinition() == typeof(IA<>).GetGenericTypeDefinition());
    }
}

定義:

interface IA<T>
{
    T Foo();
}

class Baz1 { }
class Baz2 { }

class Bar : IA<Baz1>, IA<Baz2>
{
    Baz2 IA<Baz2>.Foo()
    {
        return new Baz2(); 
    }

    Baz1 IA<Baz1>.Foo()
    {
        return new Baz1(); 
    }
}

碼:

    Bar b = new Bar();
    var methods = typeof(Bar).GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IA<>)).Select(i => i.GetMethod("Foo"));
    foreach(var method in methods)
    {
        var invoked = method.Invoke(b, null); // or add params instead of null when needed
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM