我有一个接受 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/