繁体   English   中英

如何将 Invoke 返回的值转换为 IEnumerable<type> 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 重新设计为界面。

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

像这样。 一、执行器界面:

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

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

public interface IEntityWithSomeFunction
{
    void SomeFunction();
}

现在执行executor。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM