下面小编就为大家带来一篇浅谈c#表达式树Expression简单类型比较demo。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
实例如下:
using System;
using System.Linq.Expressions;
class DynamicPredicate
{
public static Expression<Func<T, T, bool>> Generate<T>(string op)
{
ParameterExpression x = Expression.Parameter(typeof(T), "x");
ParameterExpression y = Expression.Parameter(typeof(T), "y");
return Expression.Lambda<Func<T, T, bool>>
(
(op.Equals(">")) ? Expression.GreaterThan(x, y) :
(op.Equals("<")) ? Expression.LessThan(x, y) :
(op.Equals(">=")) ? Expression.GreaterThanOrEqual(x, y) :
(op.Equals("<=")) ? Expression.LessThanOrEqual(x, y) :
(op.Equals("!=")) ? Expression.NotEqual(x, y) :
Expression.Equal(x, y),
x,
y
);
}
}
static void Main()
{
string op = ">=";
var integerPredicate = DynamicPredicate.Generate<int>(op).Compile();
var floatPredicate = DynamicPredicate.Generate<float>(op).Compile();
int iA = 12, iB = 4;
Console.WriteLine("{0} {1} {2} : {3}",
iA, op, iB, integerPredicate(iA, iB));
float fA = 867.0f, fB = 867.0f;
Console.WriteLine("{0} {1} {2} : {3}",
fA, op, fB, floatPredicate(fA, fB));
Console.WriteLine("{0} {1} {2} : {3}",
fA, ">", fB, DynamicPredicate.Generate<float>(">").Compile()(fA, fB));
Console.ReadLine();
}
以上这篇浅谈c#表达式树Expression简单类型比较demo就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:浅谈c#表达式树Expression简单类型比较demo
基础教程推荐
猜你喜欢
- ZooKeeper的安装及部署教程 2023-01-22
- C# List实现行转列的通用方案 2022-11-02
- winform把Office转成PDF文件 2023-06-14
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- C# 调用WebService的方法 2023-03-09
- C#类和结构详解 2023-05-30
- C# windows语音识别与朗读实例 2023-04-27
- 一个读写csv文件的C#类 2022-11-06
- C#控制台实现飞行棋小游戏 2023-04-22
- unity实现动态排行榜 2023-04-27