【问题标题】:Conversion of object array to Generic array typeof T Type at runtime C#在运行时 C# 将对象数组转换为 T 类型的通用数组类型
【发布时间】:2016-02-15 22:48:25
【问题描述】:

我试图在运行时将一种对象类型转换为 T 类型,但我玩得很开心。创建方法被调用并且应该在字典上执行一些魔术 - 为函数提供 T []、DbContext 和请求的类型作为 System.Type - 但是我通过智能感知从 Visual Studio 收到以下错误,当我尝试编译。 错误委托“System.Func”有一些无效参数。

2016 年 2 月 16 日编辑

我不明白无效参数是什么——因为我在 DbContrext 中传递了一个 System.Type 和一个通用 T[]——如果我从字典函数中删除 System.Type 参数并将其保留为参数 T[ ] - 传入对象就可以了!所以我的假设是它与传递 System.Type 或 params 语句的某些方式有关 - 但我不知道 - 请参阅我微弱的转换尝试的代码,并查看 非常小的底部 我研究工作的一部分。

有没有人知道我可以使用上面的字典函数的一种方法——不使用对 Create 方法的通用调用,换句话说,我不能传入 T[],也不能将它作为 Create 传递;它必须采用方法签名的形式(只要方法签名中没有使用泛型,就可以使用变体)。

以下代码:

    private Dictionary<Operator, Func<T[], DbContext, System.Type, bool> > operators =
    new Dictionary<Operator, Func<T[], DbContext, System.Type, bool> >
    {   
    { Operator.Update, ( a , b, c ) => {// do work with abc} }

    } 


public bool Create(DbContext context, Operator op, System.Type requestedType, params object[] items )
{

    Type temp = requestedType.MakeArrayType();

    var elementsArray =  Activator.CreateInstance(temp);

    ArrayList elList = new ArrayList(items);
    for (int i = 0; i < elList.Count; i++)
    {
        Convert.ChangeType(elList[i], requestedType);
    }

    elementsArray = elList.ToArray();

    var listType = typeof(object);
    var constructedListType = listType.MakeGenericType(requestedType);

// Error Delegate 'System.Func<T[],System.Data.Entity.DbContext,System.Type,bool>' has some invalid arguments   

    return operators.ContainsKey(op) ? operators[op](items, context, requestedType) : false;

}

2016 年 2 月 16 日编辑 对于downvoters的驱动-点击下来需要很少的努力,但评论需要礼貌-我尝试过的一些链接:

How to cast object array to generic type array

Casting Type array to Generic array?

how to upcast object array to another type of object array in C#?

【问题讨论】:

    标签: c# arrays generics type-conversion


    【解决方案1】:

    我确实找到了解决方案,但我花了几个步骤来解决问题。

    虽然我确实知道错误与提供的参数有关 [显然 - 从错误消息中],但我在没有 Syste.Type 参数的情况下传入对象并且它起作用的事实让我失望。在 Dictionary 函数中添加 Type 的附加参数“C”后,它停止工作并抛出此错误 - 所以你可以想象我认为它是 System.Type argC。下面的代码显示了我为编译它所做的工作,它尚未完全测试,但它已经编译,所以我更进一步:

    public bool Create(DbContext context, Operator op, System.Type requestedType, params object[] items)
    {
        T[] itemsArray = (T[])new Object[items.Length];
    
        itemsArray = items.Select(eachObject => (T)eachObject).ToArray();
    
        return operators.ContainsKey(op) ? operators[op](itemsArray, context, requestedType) : false;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多