gpt4 book ai didi

C# Linq 将匿名类型转换到接口(interface)上

转载 作者:太空狗 更新时间:2023-10-29 18:32:43 25 4
gpt4 key购买 nike

是否可以使用 Select 将其投影到匿名类型上?

下面是一些示例代码

public interface ITest
{
string A{get;}
int B{get;}
}

string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
IQueryable<ITest> query =
from n in names.AsQueryable()
select new {A = n.ToUpper(), B = 2012};

上面的代码导致了一个

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'

注意:如果我要定义一个实现 ITest 的类 Test,然后使用以下方法转换到该类中,我可以使上面的代码工作:

select   new Test {A = n.ToUpper(), B = 2012};

为什么?我想看看我是否可以只定义接口(interface)而不必定义对象的具体实现并让 Linq 为我创建对象。

最佳答案

是的,您可以选择一个匿名类型,但您不能既选择一个匿名类型,又像它们实现了一个接口(interface)一样使用这些对象。原因是匿名类型不实现接口(interface),即使它们在类型和名称上具有相同的属性。没有办法定义匿名类型实现接口(interface)。如果你想通过它们的接口(interface)实现来使用对象,你必须选择一个实现该接口(interface)的具体类型。

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

引用:http://msdn.microsoft.com/en-us/library/bb397696.aspx

我当然可以理解您的意图。如果编译器可以凭直觉知道类型在匿名类型时符合接口(interface)定义,那会很好,但这实际上只适用于接口(interface)严格由只读属性组成的情况。在您的接口(interface)使用 setter 或方法定义属性的那一刻,匿名类型就不可能实现它。另一方面,如果您按预期使用匿名类型——作为特定用途的短期临时类型——您可以简单地引用它的属性,根本不需要接口(interface)。

 var query = from     n in names.AsQueryable()
select new {A = n.ToUpper(), B = 2012};
foreach (var item in query)
{
Console.WriteLine( item.A );
}

关于C# Linq 将匿名类型转换到接口(interface)上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8105341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com