C# 检查由类型变量定义的类型是否在.NET Portable中实现接口
我的通用应用程序中有可移植组件,因此,该组件使用.NET portable v.4.6。在该组件中,我试图检查由C# 检查由类型变量定义的类型是否在.NET Portable中实现接口,c#,.net,portable-class-library,win-universal-app,C#,.net,Portable Class Library,Win Universal App,我的通用应用程序中有可移植组件,因此,该组件使用.NET portable v.4.6。在该组件中,我试图检查由type变量myType定义的类型是否实现了某个接口IMyinterface 如果我使用的是标准的.NET框架,我可以检查myType.GetInterface(“MyClass.IMyinterface”)!=空 或者如果 (typeof(IMyinterface).IsAssignableFrom(myType))==true (见:) 但是,这些方法在.NET Portable
type
变量myType
定义的类型是否实现了某个接口IMyinterface
如果我使用的是标准的.NET框架,我可以检查myType.GetInterface(“MyClass.IMyinterface”)!=空
或者如果
(typeof(IMyinterface).IsAssignableFrom(myType))==true
(见:)
但是,这些方法在.NET Portable v.4.6中不可用。你知道我如何在这种情况下执行此检查吗?这不会引发异常,但是,myType现在可以为null
var myObject = myType as IMyinterface
//Error proof the assignment to interface.
if (typeof(IMyinterface) == myType.GetType())
{
//code
}
或
或
我想您需要使用添加以下内容:
using System.Reflection;
然后像这样做检查:
(typeof(IMyinterface).GetTypeInfo().IsAssignableFrom(myType.GetTypeInfo())) == true
我测试了这些,但它们对我不起作用。我假设在上面的所有检查中,您的意思是检查
myObject
,而不是myType
?问题是无论Type myType
是否实现接口IMyinterface
,myObject总是null
。
using System.Reflection;
(typeof(IMyinterface).GetTypeInfo().IsAssignableFrom(myType.GetTypeInfo())) == true