在c#中测试对象是否实现给定接口的最简单方法是什么?(回答这个问题 在Java中)
当前回答
最近我试着用安德鲁·凯南的答案,但出于某种原因,它对我不起作用。我使用了这个方法,并且它有效(注意:可能需要写入名称空间)。
if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)
其他回答
这应该可以工作:
MyInstace.GetType().GetInterfaces();
但也很好:
if (obj is IMyInterface)
甚至(不是很优雅):
if (obj.GetType() == typeof(IMyInterface))
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)
对我有用的是:
断言。IsNotNull (typeof (YourClass) .GetInterfaces()。(i => i == typeof (ISomeInterface)));
我通过使用is关键字实现了这一点。
但是我也需要一个新的对象来使用接口属性。 要实现这一点,您需要在Interface之后添加新变量。
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.
}
}
我使用
断言。(myObject是ImyInterface);
在我的单元测试中测试myObject是一个实现了我的接口ImyInterface的对象。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和