c# - 如果 <T> 是动态的,我如何测试 Enumerable<T> 中的 <T> 是否实现了接口(interface)?

标签 c# generics interface ienumerable

我有一个接受 IEnumerable<dynamic> 的方法

有没有办法在方法内部测试动态类型,看看它是否实现了特定的接口(interface)?

我的意图是这样的:

public void myMethod(IEnumerable<dynamicT> enumerable)
{
    if (dynamicT is IInterface)
    {
        // do one thing
    }
    else if (dynamicT is IAnotherInterface)
    {
        // do another thing
    }
}

更新

我应该包括这个重要的事实:<T>是动态的。

请原谅,我正在编码的地方已经接近午夜了。 :-$

最佳答案

您可以使用 Type.IsAssignableFrom方法:

Determines whether an instance of the current Type can be assigned from an instance of the specified Type.

public void myMethod(IEnumerable<T> enumerable)
{
    if (typeof(IInterface).IsAssignableFrom(typeof(T))
    {
        // do one thing
    }
    else if (typeof(IAnotherInterface).IsAssignableFrom(typeof(T))
    {
        // do another thing
    }
}

关于c# - 如果 <T> 是动态的,我如何测试 Enumerable<T> 中的 <T> 是否实现了接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357706/

相关文章:

c# - ShellFile.FromFilePath 中的奇怪错误

c# - 如何修复 CA1000 不要在泛型类型上声明静态成员

generics - 带有数组的 Swift countElements()

c++ - 如何在 C++ 中使用模板函数实现父类?

c++ - 通用 API 发布技术

c# - 系统.LINQ.动态 : Select (“new classname (…)” ) into a List<T> (or any other enumerable collection of <T>)

c# - 如何添加、编辑和删除集合中的项目?

c# - 通用方法和非通用方法之间的性能差异

c# - 在泛型类实例化上创建了多少个实例?

php - 实现接口(interface)和自动加载类