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

函数返回一个generics类型,其值仅在运行时已知分享

时间:2023-04-10 11:11:44 C#

C#学习教程:函数返回一个泛型类型,其值只在运行时知道>内容{得到;实现此接口的对象由以下泛型方法返回:IContainerGetContainer(IPropertyproperty);类型T在运行时之前是未知的。使用反射,我可以调用GetContainer方法并获得结果。我的问题是我不知道如何枚举类型为Object的结果(因此我无法将其设为IEnumerable)。我也试过如下进行转换,但它不起作用(它说“预期类型”):其中type是运行时类型,myService是公开GetContainer方法的服务,property是IProperty类型。更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/typeof(IContainer)。MakeGenericType(type)仅在运行时评估,而“as”需要在编译时知道类型。我真正不明白的是这条评论:我的问题是我不知道如何枚举类型为Object的结果(因此我无法将其转换为IEnumerable)。myContainer可能是一个对象,但它肯定可以转换为IEnumerable吗?如果不能,则无法枚举。你的类型T必须被编译器知道,所以这是行不通的。您可以尝试制作一个非通用版本的界面,如下所示:publicinterfaceIContainer{IEnumerableContents{get;}}publicinterfaceIContainer:IContainer{...}所以你可以投射并能够使用它。首先,转换时需要一个类型(double,int);typeof接受一个类型参数并返回一个Type类型的类。对象x=0.0;输入t=typeof(double);双y=x作为t;//不编译-t不是一个类型-它是类型Doubley=xastypeof(double);的一个实例//同上doubley=xasdouble;//编译-double是一个类型Typez=xasType;//compiles-Typeisatype其次,这是一些示例代码:usingSystem;使用System.Collections.Generic;使用系统集合;使用System.Reflection;使用系统诊断;命名空间TryThis{公共接口IContainer{IEnumerable>内容{get;}}publicinterfaceIContent{TGetMyContent();}publicinterfaceIProperty{}publicclassContent:IContent{Tm_content=default(T);publicTGetMyContent(){返回m_content;}publicContent(Tval){m_content=val;}}publicclassContents:IEnumerable>{List>m_contents=newList>();IEnumerator>IEnumerable>.GetEnumerator(){返回m_contents.GetEnumerator();}IEnumeratorIEnumerable.GetEnumerator(){返回m_contents.GetEnumerator();}publicContents(paramsT[]contents){foreach(Titemincontents)m_contents.Add(newContent(item));}}publicclassTestGenericContent:IContainer{publicIContainerGetContainer(IPropertyproperty){返回这个;}publicIEnumerable>Contents{get{returnnewContents(1,2,3);}}}publicstaticclassTryThisOut{staticvoidTest2(objecto){Typet=o.GetType();输入tInterface=t.GetInterface("IContainer`1");//如果o没有实现IContainer类型,则可以为nulltGenericArg=tInterface.GetGenericArguments()[0];//从IContainerMethodInfo中提取Tinfo=t.GetMethod("GetContainer");IPropertypropArg=null;//null在这个例子中objectoContainer=info.Invoke(o,newobject[]{propArg});PropertyInfoprop=tInterface.GetProperty("内容");objectoContents=prop.GetGetMethod().Invoke(oContainer,null);//oContents是IEnumerable>类型,派生自IEnumerable,所以我们可以强制转换IEnumerableenumeratedCon内容=oContents作为IEnumerable;MethodInfogetContentItem=typeof(IContent).MakeGenericType(tGenericArg).GetMethod("GetMyContent");foreach(enumeratedContents中的对象项目){objectoContentItem=getContentItem.Invoke(item,nullrint);“{1}类型的项目{0}”,oContentItem,oContentItem.GetType());//...}}publicstaticvoidTest(){objecto=newTestGenericContent();测试2(o);如果您正在考虑迁移到动态类型提供的.Net4,我假设您的对象只会作为有限数量的类型之一返回,所以为什么不在转换之前测试它们,例如如果对象是这个类?抱歉,如果我误解了,我无法确切理解您的目标是什么。你在找这样的东西吗?以上就是C#学习教程:函数返回泛型,其值只有运行时才知道分享所有内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——varmyContainer=typeof(ClassWithGetContainer).GetMethod("GetContainer").MakeGenericMethod(runtimeType).Invoke(InstanceOfClassWithGetContainer,new对象[]{属性});本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: