函数返回一个泛型类型,其值只在运行时已知 [英] Function returning a generic type whose value is known only at runtime

查看:143
本文介绍了函数返回一个泛型类型,其值只在运行时已知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用像下面这样的通用接口:

I need to use a generic interface like the following:

public interface IContainer<T>
{
    IEnumerable<IContent<T>> Contents { get; }
}



实现此接口的对象由类似以下的通用方法返回:

An object implementing this interface is returned by a generic method like the following:

IContainer<T> GetContainer<T>(IProperty property);



键入 T 是未知的,直到运行时

Type T is unknown until run-time.

使用反射,我能够调用 GetContainer< T> 方法得到的结果。

Using reflection I am able to invoke the GetContainer<T> method and get the result.

我的问题是,我不知道如何枚举其类型为对象(所以我不能结果它转换为的IEnumerable )。

My problem is that I don't know how to enumerate the result which has type Object (therefore I cannot cast it to IEnumerable).

我也试着铸造如下,但它不工作(它说类型预计):

I have also tried casting as follows but it does not work (it says "Type is expected"):

var myContainer = genericMethodInfo.Invoke(
                           myService, 
                           new object[] { property })
    as typeof(IContainer<>).MakeGenericType(type);



其中,键入是运行时类型,为myService 是服务暴露 GetContainer< T> 方法,以及属性的类型的iProperty 的需要。

where type is the runtime type, myService is the service exposing the GetContainer<T> method, and property is of type IProperty as needed.

更新:看到我的完整的解决方案在我的博客:的 http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

UPDATE: see my complete solution in my blog: http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

推荐答案

typeof运算(的IContainer<>)MakeGenericType(类型)将只在运行时进行评估,而为。 。需要知道在编译时的类型

typeof(IContainer<>).MakeGenericType(type) will only evaluate at runtime, while "as" needs to know the type at compiler time.

我真不明白,是这条评论:我的问题是,我不知道如何枚举其结果具有Object类型(所以我不能将它转换为IEnumerable的)。

What I really don't understand is this comment: My problem is that I don't know how to enumerate the result which has type Object (therefore I cannot cast it to IEnumerable).

myContainer中可能是一个对象,但它一定能够转换为IEnumerable的?如果它不能那么它不能枚举

myContainer may be an Object but it can surely be cast to IEnumerable? If it can't then it can't be enumerated.

这篇关于函数返回一个泛型类型,其值只在运行时已知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆