LINQ .Cast()扩展方法失败,但(类型)对象的作品 [英] LINQ .Cast() extension method fails but (type)object works

查看:198
本文介绍了LINQ .Cast()扩展方法失败,但(类型)对象的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要一些LINQ之间的转换为SQL对象,我们已经对创建的DTO显式类型转换操作符的DTO。这样,我们可以做到以下几点:

To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs. That way we can do the following:

DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj;

这工作得很好。

然而,当您尝试使用LINQ .Cast()扩展方法是trows一个无效的转换异常的说法不能投射型Linq2SQLType键入DTOType投。即低于不起作用

However when you try to cast using the LINQ .Cast() extension method it trows an invalid cast exception saying cannot cast type Linq2SQLType to type DTOType. i.e. the below does not work

List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>()
                                               .ToList();



但下面的工作正常:

But the below works fine:

DAL.tName MyDalName = new DAL.tName();
DTO.Name MyDTOName = (DTO.Name)MyDalName;

和下面也能正常工作

List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name)
                                               .ToList();



为什么.Cast()扩展方法抛出一个无效的转换异常?我已经在过去使用的.Cast()扩展方法以这种方式很多次,当你投的东西就像一个基本类型派生类型,它工作正常,但落在当对象具有显式类型转换操作符了。

Why does the .Cast() extension method throw an invalid cast exception? I have used the .Cast() extension method in this way many times in the past and when you are casting something like a base type to a derived type it works fine, but falls over when the object has an explicit cast operator.

推荐答案

演员LT;> 扩展方法不适用于用户可定义的转换。它只能转换为接口或提供类型的类层次结构内。

The Cast<> extension method does not apply user-defined conversions. It can only cast to interfaces or within the class heirarchy of the supplied type.

用户定义的转换是在根据所涉及的静态类型的编译时间确定。表达它们不能被用作运行时转换,因此下面是非法的:

User defined conversions are identified at compile time based on the static types involved in the expression. They cannot be applied as runtime conversions, so the following is illegal:

public class SomeType
{
  public static implicit operator OtherType(SomeType s) 
  { 
    return new OtherType(); 
  }
}

public class OtherType { }

object x = new SomeType();
OtherType y = (OtherType)x; // will fail at runtime



不要紧,一UDC无论从 SOMETYPE 到 OTHERTYPE - 它无法通过类型的引用适用对象。试图运行上面的代码会在运行时失败,报告是这样的:

It doesn't matter whether a UDC exists from SomeType to OtherType - it cannot be applied through a reference of type object. Trying to run the above code would fail at runtime, reporting something like:

System.InvalidCastException: 
    Unable to cast object of type 'SomeType' to type 'OtherType'

演员LT;> ()只能执行表示保留转换...这就是为什么你不能用它来应用用户定义的转换。

Cast<>() can only perform representation preserving conversions ... that's why you can't use it to apply user-defined conversions.

埃里克利珀有大约在C#行为一大篇> - 总是一个值得读

Eric Lippert has a great article about the behavior of the cast operator in C# - always a worthwhile read.

这篇关于LINQ .Cast()扩展方法失败,但(类型)对象的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆