gpt4 book ai didi

c# - 将 Linq 查询结果转换为接口(interface)

转载 作者:太空狗 更新时间:2023-10-30 00:42:46 26 4
gpt4 key购买 nike

我正在尝试编写一个 Linq(对象)查询,将结果转换为接口(interface),如下所示:

    var data = (from row in CicApplication.Vaporizer473Cache
where row.Coater == coater
select row).Cast<IVaporizerData>();

这似乎是唯一的方法,因为我无法在选择中创建接口(interface)的实例。我有两个问题:

  1. 类型转换实际上是如何完成的?它会找到源中的每个属性并将其值复制到具有相同名称的接口(interface)属性吗?

  2. 我的界面中有一个属性未包含在源代码中,但我想在此操作期间以某种方式设置它的值。这可能吗?还是我需要在查询之后在 for each 语句中执行此操作?

如果有帮助,数据源 (Vaporizer473Cache) 的类定义如下所示。界面非常相似。

internal class Vaporizer473
{
/// <summary>
/// Gets or sets the Coater property
/// </summary>
public string Coater { get; set; }

/// <summary>
/// Gets or sets the CoaterTime property
/// </summary>
public DateTime? CoaterTime { get; set; }

/// <summary>
/// Gets or sets the TemperatureLeftTubeA property
/// </summary>
public double? TemperatureLeftTubeA { get; set; }

/// <summary>
/// Gets or sets the TemperatureLeftTubeB property
/// </summary>
public double? TemperatureLeftTubeB { get; set; }

/// <summary>
/// Gets or sets the TemperatureRightTubeA property
/// </summary>
public double? TemperatureRightTubeA { get; set; }

/// <summary>
/// Gets or sets the TemperatureRightTubeB property
/// </summary>
public double? TemperatureRightTubeB { get; set; }

最佳答案

即使编译器不会提示您提供的语法,它也不会运行。您不能将对象强制转换为它未实现的接口(interface)。

Cast 方法只是一个方便的方法,它尝试将给定 IEnumerable 中的每个对象转换为您提供的通用类型。如果 Vaporizer473 确实实现了 IVaporizerData,那么您可以轻松地说:

var data = from row in CicApplication.Vaporizer473Cache
where row.Coater == coater
select (IVaporizerData)row;

其次:

I have a property in my interface that isn't contained in the source, but I would like to somehow set its value during this operation. Is this possible? Or do I need to do it after the query, in a for each statement?

您现在已经知道,您的类必须在您的界面中实现该属性。 (您可以这样做 explicitly,这样它就不会在您的实际类实现等上占用智能感知。)可以通过使用复杂的 Select 委托(delegate),但这不是 LINQ 的目的,我强烈反对它。在这种情况下,for 循环是合适的做法。

请记住,如果您修改来自缓存的项目,您将修改原始对象而不是它们的克隆。这可能会产生深远的影响。您可能想要创建新对象来表示您正在寻找的数据。

关于c# - 将 Linq 查询结果转换为接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827091/

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