转换表达式< func< t,object>>到字符串

发布于 2025-02-04 03:37:43 字数 779 浏览 0 评论 0原文

我尝试以expression< func< persock>>将表达式转换为以后操作的字符串。

此表达式存储在类的属性中,并用于源代码生成。

示例1(这是按预期起作用的)

Expression<Func<Person,object>> exp1 = p => "abc";  
Console.WriteLine(exp1.ToString() ); // ok, p => "abc"

示例2(这具有预期的结果):

Expression<Func<Person,object>> exp2 = p =>  Guid.NewGuid();
Console.WriteLine(exp2.ToString()); 
//the string is including a convert method:  p => Convert(NewGuid(), Object)

我希望表达式为p =&gt; guid.newguid(),不包括convert方法:f =&gt; convert(newguid(),对象)

转换方法中的问题是字符串表达式不可用,并且在生成的新源代码中导致汇编错误。

我需要做什么才能按照:f =&gt; Guid.NewGuid()没有转换方法?

a

I try to convert an expression in the form Expression<Func<Person,object>> to a string for later manipulation.

This expression is stored in a property in a class and it's used in source code generation.

Example 1 (This works as expected)

Expression<Func<Person,object>> exp1 = p => "abc";  
Console.WriteLine(exp1.ToString() ); // ok, p => "abc"

Example 2 (This has a result that is not expected):

Expression<Func<Person,object>> exp2 = p =>  Guid.NewGuid();
Console.WriteLine(exp2.ToString()); 
//the string is including a convert method:  p => Convert(NewGuid(), Object)

I expect expression to be p => Guid.NewGuid(), without including the Convert method: f=> Convert(NewGuid(), Object)

The problem in the Convert method is the string expression is un usable and cause a compilation error in the new source code generated.

What do I need to do to get the expression as is: f => Guid.NewGuid() without a Convert method?

Demo for a test case

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空气里的味道 2025-02-11 03:37:43

通过使用仿制药,您可能会得到所需的东西。

这是一个片段。

    public static void Main()
    {
         var text1 = GetExpressionText(x => "abc");
         Console.WriteLine(text1);
         var text2 = GetExpressionText(x => Guid.NewGuid());
         Console.WriteLine(text2);
    }
    
    private static string GetExpressionText<TReturn>(Expression<Func<Person, TReturn>> expression) {
        return expression.ToString();
    }

小提琴,以便您可以进行更多的测试。

By using Generics you might get what you're looking for.

Here's a snippet.

    public static void Main()
    {
         var text1 = GetExpressionText(x => "abc");
         Console.WriteLine(text1);
         var text2 = GetExpressionText(x => Guid.NewGuid());
         Console.WriteLine(text2);
    }
    
    private static string GetExpressionText<TReturn>(Expression<Func<Person, TReturn>> expression) {
        return expression.ToString();
    }

A fiddle so you can do some more testing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文