簡體   English   中英

檢查對象是否實現特定的通用接口

[英]Check if object implements specific generic interface

我有多個類(為便於說明而簡化):

public class A : BaseClass,
    IHandleEvent<Event1>,
    IHandleEvent<Event2>
{
}

public class B : BaseClass,
    IHandleEvent<Event3>,
    IHandleEvent<Event4>
{
}

public class C : BaseClass,
    IHandleEvent<Event2>,
    IHandleEvent<Event3>
{
}

在我的“ BaseClass”中,我有一個方法要檢查Child-class是否實現特定事件的IHandleEvent

public void MyMethod()
{
    ...
    var event = ...;
    ...
    // If this class doesn't implement an IHandleEvent of the given event, return
    ...
}

這個SO-answer中,我知道如何檢查對象是否實現了通用接口(實現IHandleEvent<> ),如下所示:

if (this.GetType().GetInterfaces().Any(x =>
    x.IsGenericType && x.GenericTypeDefinition() == typeof(IHandleEvent<>)))
{
    ... // Some log-text
    return;
}

但是,我不知道如何檢查對象是否實現了SPECIFIC通用接口(實現IHandleEvent<Event1> )。 那么,如何在if中檢查呢?

只需我們的isas運算符:

if( this is IHandleEvent<Event1> )
    ....

或者,如果在編譯時不知道type參數:

var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
    ....

暫無
暫無

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

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