【问题标题】:Expression.Default in .NET 3.5.NET 3.5 中的 Expression.Default
【发布时间】:2010-05-14 19:20:28
【问题描述】:

如何在 3.5 中模拟 Expression.Default(.NET 4.0 中的新功能)?

是否需要手动检查表达式类型并为引用和值类型使用不同的代码?

这是我目前正在做的,有没有更好的方法?

Expression GetDefaultExpression(Type type)
{
    if (type.IsValueType)
        return Expression.New(type);
    return Expression.Constant(null, type);
}

【问题讨论】:

  • 你能提供一个 C# 4.0 的例子吗?
  • @Simon Expression.Default(typeof(int)) 和 Expression.Default(typeof(Window))

标签: linq .net-3.5


【解决方案1】:

你做的很好。 .NET Framework 中没有内置的 Type.GetDefaultValue() 方法,因此确实需要对值类型进行特殊情况处理。

也可以为值类型生成常量表达式:

Expression GetDefaultExpression(Type type) 
{ 
    if (type.IsValueType) 
        return Expression.Constant(Activator.CreateInstance(type), type); 
    return Expression.Constant(null, type); 
} 

我想这样做的好处是值类型只在第一次构建表达式树时实例化一次,而不是在每次评估表达式时。但这是吹毛求疵。

【讨论】:

  • 我喜欢优化,无论多小 :-)
【解决方案2】:

使用扩展方法怎么样?

using System;
using System.Linq.Expressions;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(int);
            Expression e = t.Default(); // <-----
            Console.WriteLine(e);
            t = typeof(String);
            e = t.Default();            // <-----
            Console.WriteLine(e);
            Console.ReadLine();
        }
    }

    public static class MyExtensions
    {
        public static Expression Default(this Type type)
        {
            if (type.IsValueType)
                return Expression.New(type);
            return Expression.Constant(null, type);
        }
    } 
}

【讨论】:

  • 嗯,那是一样的,但有一个this 限定符:-) 我想知道是否有更好的方法(猜不出来)
猜你喜欢
  • 2014-08-25
  • 2012-04-24
  • 1970-01-01
  • 2012-11-24
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多