C#将Lambda表达式函数转换为描述性字符串 [英] C# Converting Lambda Expression Function to Descriptive String

查看:327
本文介绍了C#将Lambda表达式函数转换为描述性字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不必要的困境.我正在懒惰地寻找将lamda表达式转换为字符串的函数.我每次都在输入此缓存键时感到困扰,但是我真的不想花时间创建它.

I have quite an unnecessary dilemma. I'm lazily looking for a function that would convert a lamda expression into a string. It bothers me that I'm typing in this cache key every time but I don't really want to take the time to create it.

我想将其用于我创建的缓存功能:

I want to use it for a cache function I created:

如果我想为一个人取个名字而不必每次都调用该函数.

Where if I wanted to get a name for a person without calling the function every time.

public static string GetPersonName(int id)
{
    return Repository.PersonProvider.Cached(x => x.GetById(id)).Name;
}

GetExpressionDescription将返回"PersonProvider.GetById(int 10)"

The GetExpressionDescription would return "PersonProvider.GetById(int 10)"

我认为这是有可能的,但是我想知道是否有人已经建造了它或在某个地方看到了它.

I figure this is possible but I wonder if anyone has already built this or has seen it somewhere.

public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, double hours = 24)
{
    var expressionDescription = GetExpressionDescription(function); 
    return Cached(function, expressionDescription, hours); 
}

public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, string cacheName, double hours = 24)
{
    var context = HttpContext.Current;
    if (context == null)
        return function.Compile().Invoke(obj);

    R results = default(R);
    try { results = (R)context.Cache[cacheName]; }
    catch { }
    if (results == null)
    {
        results = function.Compile().Invoke(obj);
        if (results != null)
        {
            context.Cache.Add(cacheName, results, null, DateTime.Now.AddHours(hours),
                              Cache.NoSlidingExpiration,
                              CacheItemPriority.Default, null);
        }
    }
    return results;
}

推荐答案

您可以简单地使用.ToString()获得Expression<>的字符串表示形式:

You can simply get a string representation of an Expression<> with .ToString():

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        Test(s => s.StartsWith("A"));
    }

    static void Test(Expression<Func<string,bool>> expr)
    {
        Console.WriteLine(expr.ToString());
        Console.ReadKey();
    }
}

打印:

s => s.StartsWith("A")

s => s.StartsWith("A")

请参阅: https://dotnetfiddle.net/CJwAE5

但是,当然,它不会产生调用方和变量值,而只是表达式本身.

But of course it will not yield you the caller and the values of variables, just the expression itself.

这篇关于C#将Lambda表达式函数转换为描述性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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