我们可以修改这个代码返回的方法,而不是属性的名称? [英] Can we modify this code to return the name of a method instead of a property?

查看:127
本文介绍了我们可以修改这个代码返回的方法,而不是属性的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一个干净的方式来发现在类型安全的方式方法的字符串名称。



下面是我对物业,但我有麻烦搞清楚如何做到这一点的方法。

 类节目
{
类客户
{
公共字符串ID {搞定;组; }
}

公共静态字符串getPropertyName方法< T>(
表达式来; Func键< T,对象>>选择器),其中T:类
{
VAR表达式=(MemberExpression)selector.Body;
返回expression.Member.Name;
}

静态无效的主要(字串[] args)
{
字符串参数propertyName = getPropertyName方法<客户>(C => c.Id);
}
}


解决方案

漂亮备受更改为:

  VAR表达式=(MethodCallExpression)selector.Body; 
返回expression.Method.Name;



与显着的例外,您将需要一个动作< T> 选项来处理无效方法。你将不得不提供假的参数值,当然 - 如果你的真正的希望你能得到那些过于



其实,您的现有的的代码可能不会强劲;你可能需要扔掉转换操作(框整型到一个对象)

 公共静态字符串GetMethodName< T> (表达式来; Func键< T,对象>>选择器),其中T:类
{
VAR表达式=(MethodCallExpression)(selector.Body是UnaryExpression((UnaryExpression)selector.Body).Operand: selector.Body);
返回expression.Method.Name;
}
公共静态字符串GetMethodName< T>(表达<作用< T>>选择器),其中T:类
{
VAR表达式=(MethodCallExpression)(selector.Body是UnaryExpression((UnaryExpression)selector.Body).Operand:selector.Body);
返回expression.Method.Name;
}


Looking for a clean way to discover the string name of a method in a type safe way.

Here is what I have for properties, but I'm having trouble figuring out how to do it for methods.

class Program
{
    class Customer
    {
        public String Id { get; set; }
    }

    public static String GetPropertyName<T>(
        Expression<Func<T, Object>> selector) where T : class
    {
        var expression = (MemberExpression)selector.Body;
        return expression.Member.Name;
    }

    static void Main(string[] args)
    {
        String propertyName = GetPropertyName<Customer>(c => c.Id);
    }
}

解决方案

Pretty much by changing to:

    var expression = (MethodCallExpression)selector.Body;
    return expression.Method.Name;

with the notable exception that you will need an Action<T> option to handle void methods. You will have to supply dummy parameter values, of course - if you really want you can obtain those too.

Actually, your existing code might not be robust; you may need to throw away a cast operation (to box the int to an object).

public static string GetMethodName<T>(Expression<Func<T, Object>> selector) where T : class
{
    var expression = (MethodCallExpression)(selector.Body is UnaryExpression ? ((UnaryExpression)selector.Body).Operand : selector.Body);
    return expression.Method.Name;
}
public static string GetMethodName<T>(Expression<Action<T>> selector) where T : class
{
    var expression = (MethodCallExpression)(selector.Body is UnaryExpression ? ((UnaryExpression)selector.Body).Operand : selector.Body);
    return expression.Method.Name;
}

这篇关于我们可以修改这个代码返回的方法,而不是属性的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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