【问题标题】:C# expression gets converted into different expression by itselfC# 表达式自行转换为不同的表达式
【发布时间】:2018-07-05 02:58:27
【问题描述】:

我有以下模型类:

public class Post
{
    public long Id { get; set; }
    public string AuthorId { get; set; }
    public DateTime CreatedAt { get; set; }
    public string Text { get; set; }

    public User Author { get; set; }
    public IReadOnlyCollection<PostRating> Ratings { get; set; }

    public IReadOnlyCollection<PostAction> UserPermissions { get; set; }
}

我需要使用表达式公开一些属性,除了 CreatedAt 之外,所有属性似乎一切正常。当我需要公开该表达式时,该表达式会以某种方式转换为另一种表达式。

我认为最好只显示我的代码图片以及调试器看到的值。

如您所见,CreatedAt 属性表达式发生了一些奇怪的事情。 但是如果我将该表达式的类型更改为Expression&lt;Func&lt;Post, DateTime&gt;&gt;,它就可以工作。

【问题讨论】:

标签: c# expression


【解决方案1】:

您可能会遇到拳击问题。 The documentation 有更多内容,但基本上装箱是将值类型(如您的 DateTime)转换为 object 的过程。这是一种隐式转换,可以解释为什么您会看到这种行为。如果不希望这样做,您最好在表达式中使用该类型。

【讨论】:

  • Post.AuthorId 是一个string,它是一个引用类型。
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多