在c#中测试对象是否实现给定接口的最简单方法是什么?(回答这个问题 在Java中)
当前回答
这应该可以工作:
MyInstace.GetType().GetInterfaces();
但也很好:
if (obj is IMyInterface)
甚至(不是很优雅):
if (obj.GetType() == typeof(IMyInterface))
其他回答
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
我通过使用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.
}
}
例如:
if (obj is IMyInterface) {}
本课程:
检查typeof(MyClass). getinterfaces()是否包含该接口。
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)
如果您在编译时就知道接口类型,并且拥有正在测试的类型的实例,那么使用is或作为操作符是正确的方法。其他人似乎没有提到的是类型。IsAssignableFrom:
if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}
我认为这比查看GetInterfaces返回的数组要简洁得多,而且也具有适用于类的优点。
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因