[英]Test if object implements interface
if (object is IBlah)
或者
IBlah myTest = originalObject as IBlah
if (myTest != null)
如果您在编译时知道接口类型并且有您正在测试的类型的实例,则使用is
或as
运算符是正确的方法。 其他人似乎没有提到的是Type.IsAssignableFrom
:
if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}
我认为这比查看GetInterfaces
返回的数组要简洁得多,并且还具有为类工作的优势。
如果要在检查后使用类型转换对象:
从 C# 7.0 开始:
if (obj is IMyInterface myObj)
这与
IMyInterface myObj = obj as IMyInterface;
if (myObj != null)
请参阅 .NET 文档: 模式匹配概述
例如:
if (obj is IMyInterface) {}
对于班级:
检查typeof(MyClass).GetInterfaces()
包含接口。
@AndrewKennan's answer的一个变体我最近最终用于在运行时获得的类型:
if (serviceType.IsInstanceOfType(service))
{
// 'service' does implement the 'serviceType' type
}
这个帖子是一个很好的答案。
public interface IMyInterface {}
public class MyType : IMyInterface {}
这是一个简单的示例:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
或者
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
对我有用的是:
Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));
除了使用“is”运算符进行测试之外,您还可以修饰您的方法以确保传递给它的变量实现特定的接口,如下所示:
public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
//Some bubbly sorting
}
我不确定这是在哪个版本的 .Net 中实现的,所以它可能不适用于您的版本。
最近我尝试使用 Andrew Kennan 的答案,但由于某种原因它对我不起作用。 我改用它并且它起作用了(注意:可能需要编写命名空间)。
if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)
我用了
Assert.IsTrue(myObject is ImyInterface);
对于我的单元测试中的一个测试,它测试 myObject 是一个实现了我的接口 ImyInterface 的对象。
我遇到过将变量传递给方法的情况,但不确定它是接口还是对象。
目标是:
我通过以下方式实现了这一点:
if(!typeof(T).IsClass)
{
// If your constructor needs arguments...
object[] args = new object[] { my_constructor_param };
return (T)Activator.CreateInstance(typeof(T), args, null);
}
else
return default(T);
我通过使用is
关键字实现了这一点。
但我还需要一个新对象来使用接口属性。 为此,您需要在接口之后添加新变量。
objectToCheck is Interface newVariableWithInterfaceProperties
.
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
if (request is ICacheableQuery cachableRequest)
{
// here cachableRequest now has the interface properties.
}
}
interface IItem
{
}
class ItemImp : IItem
{
}
class Program
{
static void Main(string[] args)
{
Type t = typeof(ItemImp);
Console.WriteLine("t == typeof(IItem) -> {0}", t == typeof(IItem));
Console.WriteLine("typeof(IItem).IsAssignableFrom(t) -> {0}", typeof(IItem).IsAssignableFrom(t));
Console.WriteLine("t is IItem -> {0}", t is IItem);
Console.WriteLine("new ItemImp() is IItem -> {0}", new ItemImp() is IItem);
}
}
// Here are outputs:
// t == typeof(IItem) -> False
// typeof(IItem).IsAssignableFrom(t) -> True
// t is IItem -> False
// new ItemImp() is IItem -> True
这应该工作:
MyInstace.GetType().GetInterfaces();
但也不错:
if (obj is IMyInterface)
甚至(不是很优雅):
if (obj.GetType() == typeof(IMyInterface))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.