本文介绍了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()扩展方法,它抛出一个无效的铸造异常,不能铸造类型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();

但以下工作正常:

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.

推荐答案

铸造<> 定义转化。

用户定义的转换在编译时根据所涉及的静态类型来标识。 。它们不能用作运行时转换,因此以下是非法的:

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 - 不能通过类型 object 的引用应用。尝试运行上面的代码将在运行时失败,报告如下:

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'

铸造< ()只能执行表示保留转换...这就是为什么您无法使用它来应用用户定义的转化。

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

Eric Lippert有关于 - 总是值得阅读。

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

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

10-27 03:51