将C#LINQ表达式同时用于值类型和引用类型 [英] Using C# LINQ Expressions for both Value Types and Reference Types

查看:70
本文介绍了将C#LINQ表达式同时用于值类型和引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将MVC用于REST,以便可以利用Razor输出不同的类型. CSV是这些输出之一.而不是为每种输入类型编写此模板:

I'm using MVC for REST so that I can take advantage of Razor for outputting different types. CSV is one of those outputs. Instead of writing this template for each input type:

ID,Created,Content
@foreach (var item in Model.TimeData)
{
<text>@item.ID,@item.Created,"@Html.Raw(item.Content.Replace("\"", "\"\""))"</text>
}

我想利用paramsSystem.Linq.Expressions.Expression来写这样的东西:

I wanted to make use of params and System.Linq.Expressions.Expression to write something like this:

@{
    Html.WriteCsv<TimeObject>(Model.TimeData, p => p.ID, p => p.Created, p => p.Content);   
}

我开始编写泛型HtmlHelper,并很快意识到我在值类型方面遇到了问题(memberExpression将为null).下面的代码试图只写出CSV标题(ID,Created,Content),但只输出"Content"(因为ID和Created是值类型(intDateTime).

I started writing a generic HtmlHelper and quickly realized I had problems with value types (memberExpression will be null). The code below attempts to just write out the CSV heading (ID,Created,Content), but it only outputs "Content" (because ID and Created are value types (int and DateTime).

public static void WriteCsv<TModel>(this HtmlHelper htmlHelper, List<TModel> list, params Expression<Func<TModel, object>>[] expressions)
{
    foreach (var expression in expressions)
    {
        MemberExpression memberExpression = expression.Body as MemberExpression;

        if (memberExpression != null)
        {
            var propertyInfo = (PropertyInfo)memberExpression.Member;

            htmlHelper.ViewContext.Writer.Write(propertyInfo.Name + Environment.NewLine);
        }
    }
}

我试图用dynamic替换object,认为可以,但是当我快速观察expression.Body时,似乎仍然认为它正在处理一个对象(DebugView属性是(System.Object)$p.ID).

I tried replacing object with dynamic, thinking that would work, but when I quick watch expression.Body, it still seems to think it's dealing with an object (the DebugView property is (System.Object)$p.ID).

在C#4.0中这不可能吗?

Is this impossible in C# 4.0?

这是我在以下类型上使用的类型:

Here's the type I'm using it on:

[DataContract(IsReference = true, Namespace = "urn:test:TimeObject")]
public class TimeObject
{
    [DataMember]
    public long ID { get; set; }

    [DataMember]
    public string Content { get; set; }

    [DataMember]
    public DateTime Created { get; set; }
}

推荐答案

在表达式引用值类型的情况下,编译器必须将引用装箱.它隐式地这样做.这种复杂性意味着Value Type成员表达式的表达式树不仅仅是一个MemberExpression,因此您的演员表返回的是null.

In the case that the expression references a value type, the compiler has to box the reference; it does so implicitly. This complication means that the expression tree for a Value Type member expression is not simply a MemberExpression, so your cast is returning null.

以下是从

这篇关于将C#LINQ表达式同时用于值类型和引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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