is 关键字用于 object 而 reflection 用于 类型:
您可以使用typeof(T).GetInterfaces() 来拉取应用于特定类型的所有接口。
public void MyMethod(IEnumerable<T> enumerable)
{
var typeInterfaces = typeof(T).GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
============根据评论更新============
如果 T 是动态,则您无法从类型本身获得您正在寻找的信息,因为 T 可以代表任意数量的不同类型同时进行。
但是,您可以遍历每个元素并使用 is 关键字测试对象本身。
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
foreach (var dynObj in enumerable)
{
var typeInterfaces = dynObj.GetType().GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
}
或者,如果您只想测试枚举中所有可能的接口,您可以这样做:
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
var allInterfaces = enumerable.SelectMany(e => e.GetType().GetInterfaces()).ToList();
if (allInterfaces.Contains(typeof(ITheFirstInterface)))
{
Console.WriteLine("Has The First Interface");
}
if (allInterfaces.Contains(typeof(ITheSecondInterface)))
{
Console.WriteLine("Has The Second Interface");
}
}