.NET 3.5中的Expression.Default
问题描述:
如何在3.5中模拟Expression.Default
(.NET 4.0中的新增功能)?.NET 3.5中的Expression.Default
我是否需要手动检查表达式类型并使用不同的代码作为引用和值类型?
这就是我目前正在做的,有没有更好的方法?
Expression GetDefaultExpression(Type type)
{
if (type.IsValueType)
return Expression.New(type);
return Expression.Constant(null, type);
}
答
你这样做的方式很好。正如人们所期望的那样,没有内置于.NET Framework的Type.GetDefaultValue()方法,因此值类型的特殊情况处理确实是必需的。
也可能产生值类型常数表达式:
Expression GetDefaultExpression(Type type)
{
if (type.IsValueType)
return Expression.Constant(Activator.CreateInstance(type), type);
return Expression.Constant(null, type);
}
这样做的好处,我想会是值类型是唯一实例化一次,当表达式树先建,而比每次表达评估时都要多。但这是挑剔的。
+0
我喜欢优化,不管多小:-) – 2010-06-03 01:08:09
答
如何使用扩展方法?
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);
}
}
}
+0
嗯,这只是一个'this'限定符:-)我想知道是否有更好的方法(猜测不) – 2010-05-14 23:26:27
你能提供一个C#4.0的例子吗? – 2010-05-14 19:31:46
@Simon Expression.Default(typeof(int))和Expression.Default(typeof(Window)) – 2010-05-14 19:34:46