获取方法名称使用Lambda表达式 [英] Get Method Name Using Lambda Expression

查看:390
本文介绍了获取方法名称使用Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用lambda表达式类型的方法的名称。我使用Windows身份验证基础,需要用命名空间作为一种资源和方法名作为操作的类型名称定义访问策略。这里有一个例子

I'm trying to get the name of a method on a type using a lambda expression. I'm using Windows Identity Foundation and need to define access policies with the type name with namespace as a resource and the method name as the action. Here is an example.

这是我会得到从类型名称和方法名称类型:

This is the type I would be getting the type name and method name from:

namespace My.OrderEntry {
    public class Order {
        public void AddItem(string itemNumber, int quantity) {}
    }
}

这是我想通过DSL来定义访问策略:

This is how I would like to define the access policy through a DSL:

ForResource<Order>().Performing(o => o.AddItem).AllowUsersHaving(new Claim());



从这个声明,我想获得My.OrderEntry.Order作为资源 ADDITEM作为动作。掌握空间类型名称是没有问题的,但我不认为我可以使用lambda的方法,像我试图做的。

From that statement, I would like to get "My.OrderEntry.Order" as the resource and "AddItem" as the action. Getting the type name with namespace is no problem, but I don't think I can use a lambda for a method like I'm trying to do.

public static IPermissionExp Performing<T>(
    this IActionExp<T> exp,
    Func<T, delegate???> action) {} //this is where I don't know what to define

是这样的做,甚至可能的事情? ?是否有另一种方式做这样的事情,而无需使用魔法字符串

Is this sort of thing even possible to do? Is there another way to do this sort of thing without using magic strings?

推荐答案

有两种方法可以做到这一点:

There are two ways to do this:

1:也许你认为采取各种函数功能重载动作代表(如表达式来; Func键< T,Func键< TParam1,TParam2,TReturn>> 请注意,您的来电将需要显式地指定泛型参数,要么英寸,方法调用或通过创建委托这将用于这样的:

1: You could make overloads that take the various Func and Action delegates(eg Expression<Func<T, Func<TParam1,TParam2, TReturn>>. Note that your callers would need to specify the generic parameters explicitly, either in the method call or by creating the delegate. This would be used like this:

ForResource<Order>().Performing(o => new Action<string>(o.AddItem)).AllowUsersHaving(new Claim());



< HR>

2:你可以采取表达<作用> 包含一个方法调用,并解析出<$ C $ 。C>的MethodInfo 从表达式树被称为本想这样使用:


2: You could take an Expression<Action> that contains a method call, and parse out the MethodInfo being called from the expression tree. This would be used like this:

ForResource<Order>().Performing(o => { o.AddItem(null); }).AllowUsersHaving(new Claim());

这篇关于获取方法名称使用Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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