带有 lambda 的属性构造函数

本文关键字:构造函数 属性 lambda 带有 | 更新日期: 2023-09-27 18:37:01

可以这样做

public static void SomeMethod<TFunc>(Expression<TFunc> expr)
{
    //LambdaExpression happily excepts any Expession<TFunc>
    LambdaExpression lamb = expr;
}

并在其他地方调用它,为参数传递一个 lambda:

SomeMethod<Func<IQueryable<Person>,Person>>( p=>p.FirstOrDefault());

相反,我想将表达式作为参数传递给属性构造函数是否可以执行以下操作?

class ExpandableQueryAttribute: Attribute {
    private LambdaExpression someLambda;
    //ctor
    public ExpandableQueryMethodAttribute(LambdaExpression expression) 
    {
        someLambda = expression
    } 
}
//usage:
static LambdaExpression exp = 
      (Expression<Func<IQueryable<Person>, Person>>)
        (p => p.FirstOrDefault());
[ExpandableQueryAttribute(exp)]   //error here
// "An attribute argument must be a constant expression, typeof expression
// or array creation expression of an attribute parameter type"

的目标是在属性的构造函数中指定一个方法或 lambda(即使我必须声明一个完整的命名方法并以某种方式传递方法的名称,那也可以)。

    参数
  1. 类型可以更改,但重要的是属性构造函数可以采用该参数,并以某种方式能够将其分配给 LambdaExpression 类型的字段

  2. 我希望 lambda/方法的声明位于对属性构造函数的调用或内联的正上方,这样您就不必走很远就能看到传递的内容。

所以这些替代方案会很好,但没有运气让它们工作:

public static ... FuncName(...){...}
[ExpandableQueryAttribute(FuncName)]   
// ...

//lambdas aren't allowed inline for an attribute, as far as I know
[ExpandableQueryAttribute(q => q.FirstOrDefault())]   
// ...

现有的解决方法是将数字 ID 传递给构造函数(满足"参数必须是常量"要求),构造函数使用它在以前添加表达式的字典中进行查找。 希望改进/简化这一点,但由于属性构造函数的限制,我有一种感觉,它并没有变得更好。

带有 lambda 的属性构造函数

这个

怎么样:

    class ExpandableQueryAttribute : Attribute
    {
        private LambdaExpression someLambda;
        //ctor
        public ExpandableQueryAttribute(Type hostingType, string filterMethod)
        {
            someLambda = (LambdaExpression)hostingType.GetField(filterMethod).GetValue(null); 
            // could also use a static method
        }
    }

这应该允许您将 lambda 分配给一个字段,然后在运行时将其吸收,尽管通常我更喜欢在编译时使用 PostSharp 之类的东西来执行此操作。

简单用法示例

    public class LambdaExpressionAttribute : Attribute
    {
        public LambdaExpression MyLambda { get; private set; }
        //ctor
        public LambdaExpressionAttribute(Type hostingType, string filterMethod)
        {
            MyLambda = (LambdaExpression)hostingType.GetField(filterMethod).GetValue(null);
        }
    }
    public class User
    {
        public bool IsAdministrator { get; set; }
    }
    public static class securityExpresions
    {
        public static readonly LambdaExpression IsAdministrator = (Expression<Predicate<User>>)(x => x.IsAdministrator);
        public static readonly LambdaExpression IsValid = (Expression<Predicate<User>>)(x => x != null);
        public static void CheckAccess(User user)
        {
            // only for this POC... never do this in shipping code
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
            var method = stackTrace.GetFrame(1).GetMethod();
            var filters = method.GetCustomAttributes(typeof(LambdaExpressionAttribute), true).OfType<LambdaExpressionAttribute>();
            foreach (var filter in filters)
            {
                if ((bool)filter.MyLambda.Compile().DynamicInvoke(user) == false)
                {
                    throw new UnauthorizedAccessException("user does not have access to: " + method.Name);
                }
            }
        }
    }
    public static class TheClass
    {
        [LambdaExpression(typeof(securityExpresions), "IsValid")]
        public static void ReadSomething(User user, object theThing)
        {
            securityExpresions.CheckAccess(user);
            Console.WriteLine("read something");
        }
        [LambdaExpression(typeof(securityExpresions), "IsAdministrator")]
        public static void WriteSomething(User user, object theThing)
        {
            securityExpresions.CheckAccess(user);
            Console.WriteLine("wrote something");
        }
    }

    static void Main(string[] args)
    {
        User u = new User();
        try
        {
            TheClass.ReadSomething(u, new object());
            TheClass.WriteSomething(u, new object());
        }
        catch(Exception e) 
        {
            Console.WriteLine(e);
        }
    }

这是不可能的,因为可以传递到属性的内容需要适合 CLR 的二进制 DLL 格式,并且无法对任意对象初始化进行编码。例如,对于相同的,您不能传递可为空的值。限制非常严格。

尽管不能为属性使用复杂的构造函数,但在某些情况下,work-aound 需要为该属性提供一个公共属性并在运行时更新它。

self 指向类的对象,该对象包含其属性上的一些属性。LocalDisplayNameAttribute 是一个自定义属性。

以下代码将在运行时设置我的自定义属性类的 ResourceKey 属性。然后,此时您可以覆盖DisplayName以超出所需的任何文本。

        static public void UpdateAttributes(object self)
    {
        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self))
        {
            LocalDisplayNameAttribute attr =
                prop.Attributes[typeof(LocalDisplayNameAttribute)] 
                    as LocalDisplayNameAttribute;
            if (attr == null)
            {
                continue;
            }
            attr.ResourceKey = prop.Name;
        }
    }

使用dymanic linq: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

您可以使属性的构造函数采用计算结果为表达式的字符串。