Ton*_*Nam 3 c# generics casting
问题标题可能不正确.我有以下变量
IEnumerable x = // some IEnumerable
System.Type y = // some type
Run Code Online (Sandbox Code Playgroud)
如何迭代x以生成具有y类型项的数组?
当我查看互联网时,我发现:
public T[] PerformQuery<T>(IEnumerable q)
{
T[] array = q.Cast<T>().ToArray();
return array;
}
Run Code Online (Sandbox Code Playgroud)
注意我不能调用那个方法,因为PerformQuery y是类型的System.Type,换句话说就是调用它PerformQuery<typeof(y)>(x);或者PerformQuery<y>(x);会给我一个编译器错误.
这就是我遇到这个问题的原因.我有网络服务,我发布了两件事.我想要查询的表的类型(示例typeof(Customer)),以及实际的字符串查询示例"Select*from customers"
protected void Page_Load(object sender, EventArgs e)
{
// code to deserialize posted data
Type table = // implement that here
String query = // the query that was posted
// note DB is of type DbContext
IEnumerable q = Db.Database.SqlQuery(table, query );
// here I will like to cast q to an array of items of type table!
Run Code Online (Sandbox Code Playgroud)
您可以使用表达式树:
public static class MyExtensions
{
public static Array ToArray(this IEnumerable source, Type type)
{
var param = Expression.Parameter(typeof(IEnumerable), "source");
var cast = Expression.Call(typeof(Enumerable), "Cast", new[] { type }, param);
var toArray = Expression.Call(typeof(Enumerable), "ToArray", new[] { type }, cast);
var lambda = Expression.Lambda<Func<IEnumerable, Array>>(toArray, param).Compile();
return lambda(source);
}
}
Run Code Online (Sandbox Code Playgroud)
它x => x.Cast<Type>().ToArray()为您生成,Type在运行时已知.
用法:
IEnumerable input = Enumerable.Repeat("test", 10);
Type type = typeof(string);
Array result = input.ToArray(type);
Run Code Online (Sandbox Code Playgroud)
var ObjectsOfType_y = x.OfType<object>().Where(x => x.GetType() == y);
Run Code Online (Sandbox Code Playgroud)
但请注意,这将返回一个IEnumerable<object>。没有办法解决这个问题,因为y(Type) 表示的类型在编译时是未知的。
| 归档时间: |
|
| 查看次数: |
6718 次 |
| 最近记录: |