表达式< Func> T,bool>方法参数 [英] Expression<Func<T, bool>> method argument

查看:49
本文介绍了表达式< Func> T,bool>方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用方法来返回表达式的字符串版本:

I'm trying to make a generic method that returns the string version of an expression:

public string GetExpressionString(Expression<Func<T, bool>> expr) where T: class
{
    return exp.Body.ToString();
}

无法解析符号T

如果我将 T 更改为硬编码类型,效果很好.

Works well if I change T to a hard coded type.

我想念什么?

推荐答案

您需要将 T 声明为方法的通用类型参数:

You'll need to declare T as a generic type parameter on the method:

public string GetExpressionString<T>(Expression<Func<T, bool>> exp)
    where T: class
{
    return exp.Body.ToString();
}

// call like this
GetExpressionString<string>(s => false);
GetExpressionString((Expression<Func<string, bool>>)(s => false));

或者在父类上:

public class MyClass<T>
    where T: class
{
    public string GetExpressionString(Expression<Func<T, bool>> exp)
    {
        return exp.Body.ToString();
    }
}

// call like this
var myInstance = new MyClass<string>();
myInstance.GetExpressionString(s => false);

进一步阅读:

这篇关于表达式&lt; Func&gt; T,bool&gt;方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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