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

How to cast value returned by Invoke to IEnumerable<type> where type is some variable of type T?

我有这样的情况,我想在另一个对象上调用一些通用方法并获得 IEnumerable 结果。

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 ...
}

谁能告诉我如何解决这种情况。谢谢。

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

我不能使SomeFunction成为一个通用方法,因为实际情况是我正在用System.Type迭代一些列表并在每个元素上调用lambda(即SomeFunction

您需要做一些事情才能得到您想要的。你说你想要一个 lambda,但这意味着你需要定义那个 lambda,它在你还不知道的类型上。您可以将 lambda 重新设计为一个接口。

此外,我发现定义一个完全符合我要求的通用 class 更容易。通过反射创建这个 class 的一个实例,并且只有在那里,我才能以强类型的方式实现 class 的其余部分。这消除了大多数地方的 'not knowing what type I have'。

像这样。一、执行器接口:

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

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

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();
        }
    }
}

最后,它的用法:

// Usage:
SomeContext context = new SomeContext();
Type type = typeof(SomeEntity);
var executorType = typeof(SomeFunctionExecutor<>).MakeGenericType(type);
var executor = Activator.CreateInstance(executorType) as ISomeFunctionExecutor;
if (executor != null)
{
    executor.Execute(context);
}

基本上重点是:定义一个泛型 class 来做你需要做的事情 do 知道类型,并创建这个 class 使用反射。这比你不知道类型的整个方法要容易得多。