当前位置: 首页 > 编程语言 > C#

如何判断对象的类型是否实现了IEnumerable,其中X使用Reflection派生自Base分享

时间:2023-04-10 15:46:42 C#

如何判断对象的类型是否实现了IEnumerable,其中X使用Reflection从Base派生为基类Base,我想写一个MethodTest,像这样::publicstaticIEnumerableConvert(IEnumerableenumerable){if(Test(enumerable)){returnenumerable.Cast().Select(b=>b.SomePropertyThatIsString);}返回enumerable.Cast().Select(o=>o.ToString());}...使用反射做正确的事。我确定这是所有类型接口的问题,找到第一个符合要求的接口,但我无法在其中找到通用的IEnumerable。当然,我可以考虑这个:}......但是把它当作一个思想实验。您还可以使用如下所示的LINQ查询。publicstaticboolImplementsBaseType(IEnumerableobjects){intfound=(fromiinobjects.GetType().GetInterfaces()其中i.IsGenericType&&i.GetGenericTypeDefinition()==typeof(IEnumerable)&&typeof(MyBaseClass).IsAssignableFrom(i.GetGenericArguments()[0])选择i).Count();返回(发现>0);}此代码采用以下using语句:usingSystem;使用系统集合;使用System.Collections.Generic;使用System.Linq;因为这只是一个思想实验。这是作为扩展方法的另一种实现。publicstaticclassConversionAssistants{publicstaticboolGenericImplementsType(thisIEnumerableobjects,TypebaseType){foreach(Typetypeinobjects.GetType().GetInterfaces()){if(type.IsGenericType){if(type.GetGenericTypeDefinition()==typeof(IEnumerable)){如果(baseType.IsAssignableFrom(type.GetGenericArguments()[0]))返回真;}}}返回假;您可以使用Type.FindInterfaces过滤掉一个类型实现的所有IEnumerable接口,并检查每个接口上的泛型参数(通过Type.GetGenericArguments)以查看它是Base还是继承自Base。更新:这是一些示例代码:使用系统;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Reflection;namespaceConsoleApplication1{classBase{stringProp{get;设置;}}A类:基础{}类测试:列表{}类程序{staticvoidMain(string[]args){try{Testtest=newTest();输入myType=test.GetType();//stringfilterCriteria="IEnumerable`1";输入typeA=Type.GetType("ConsoleApplication1.A");stringfilterCriteria="System.Collections.Generic.IEnumerable`1[["+typeA.AssemblyQualifiedName+"]]";//指定将接口与过滤条件进行比较的TypeFilter委托。TypeFiltermyFilter=newTypeFilter(MyInterfaceFilter);类型[]myInterfaces=myType.FindInterfaces(myFilter,filterCriteria);if(myInterfaces.Length>0){Console.WriteLine("n{0}实现接口{1}。",myType,filterCriteria);for(intj=0;j我最近写了一些需要迭代任何集合的代码。作为传统的.NET应用程序,我什至没有可用的泛型!以下是摘录:vart=objects.GetType();//与问题兼容boolisIEnumerable=false;foreach(variint.GetInterfaces()){if(i==typeof(IEnumerable)){isIEnumerable=true;休息;我发现即使像SqlParameterCollection这样的.NET1.1集合类也是IEnumerable。它还捕获通用集合,例如List,因为它们也是IEnumerable。希望这对某人有帮助。以上就是C#学习教程:如何判断对象的类型是否实现了IEnumerable,其中X使用Reflection从Base派生所有共享的内容。如果对大家有用,需要了解更多C#学习教程,希望大家多加关注——本文来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: