如何将Invoke返回的值转换为IEnumerable <type>,其中type是类型T的某个变量?

时间:2015-11-06 14:20:32

标签: c# generics reflection casting

我有这种情况,我想在另一个对象上调用一些泛型方法并得到private void SomeFunction(Type type) { var method = context.GetType() .GetMethods() .FirstOrDefault(_ => _.Name == "GetStorage" && _.IsGenericMethod); var storage = getStorage.MakeGenericMethod(type) .Invoke(context, new object[] {}) .AsEnumerable(); //Some magic needed here. Something like Cast<type>, //but type - variable //More code ... } 结果。

SomeFunction

有人可以建议我如何弄清楚这种情况。谢谢。

我已经看过这个和类似的问题了: Casting Results from Generic Method Invocation? 但他们没有回答我的问题,如何做同样的事情,当我不知道我想要投射的类型,并且类型存储为变量时。

我无法使System.Type成为通用方法,因为实际情况是我使用SomeFunction迭代某个列表并在每个元素上调用lambda(即<%= f.input :issue_date, label:false %>

1 个答案:

答案 0 :(得分:2)

您需要做一些事情来获得您想要的东西。你说你想拥有一个lambda,但这意味着你需要定义那个你还不知道的lambda。您可以将lambda重新设计为界面。

此外,我发现定义一个完全符合我想要的泛型类要容易得多。通过反射创建这个类的实例,只有那里,我可以用强类型的方式实现类的其余部分。这消除了不知道我有什么类型&#39;在大多数地方。

喜欢这个。首先,执行器接口:

Canvas

然后我需要在实体上实现的接口,可以说是lambda。

public interface ISomeFunctionExecutor
{
    void Execute(SomeContext context);
}

现在执行执行者。

public interface IEntityWithSomeFunction
{
    void SomeFunction();
}

最后,使用它全部:

public class SomeFunctionExecutor<TType> : ISomeFunctionExecutor
{
    public void Execute(SomeContext context)
    {
        var data = context.GetStorage<TType>().Cast<IEntityWithSomeFunction>();
        foreach (var item in data)
        {
            item.SomeFunction();
        }
    }
}

基本上,关键是:定义一个泛型类,在执行知道类型的地方执行您需要做的事情,并使用反射创建此类的实例。它比使用不知道类型的整个方法容易得多。