【发布时间】: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