如何使用.NET获取属性中的构造函数参数名称? [英] How to get constructor arguments name in attributes with .NET?

查看:45
本文介绍了如何使用.NET获取属性中的构造函数参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

我正在寻找一种通过名称访问参数值的方法.

I'm looking for a way to access arguments value by name.

属性如下:

[AttributeUsage(AttributeTargets.Field)]
public class EDataAttrAttribute : Attribute {

    public EDataAttrAttribute(int GroupID, int MinimumPermissionToEdit, bool ForcePersianLetter = false) {
        this.GroupID = GroupID;
        this.MinimumPermissionToEdit = MinimumPermissionToEdit; 
    }


    public int GroupID { get; private set; }
    public int MinimumPermissionToEdit { get; private set; } 

}


public class EUser {
    [EDataAttr(1, 1)]
    public string FirstName;
}


                    var attr = typeof(T).GetField("FirstName").CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EDataAttrAttribute));
                    int n = attr.ConstructorArguments.Count; // 2 !
                    int v = attr.NamedArguments.Count;       // 0 !

在不知道索引整数的情况下如何获取MinimumPermissionToEdit值.
我只知道它的名字为MinimumPermissionToEdit.

How to get MinimumPermissionToEdit value while you don't know index int.
I know only it's named MinimumPermissionToEdit.

推荐答案

您可以为此使用LINQ.此外,您将必须使用 NamedArguments 属性,而不是 ConstructorArguments :

You can use LINQ for this. Additionally, you will have to use the NamedArguments property instead of ConstructorArguments:

NamedArguments.Single(x => x.MemberName == "Name").Value

但是,要使 NamedArguments 起作用,实际上必须在使用属性时使用名称.更新的代码表明您没有这样做.

However, for NamedArguments to work, you actually have to use the names when using the attribute. Your updated code shows that you don't do this.

在这种情况下,无法通过名称获取值.您只需要使用索引.与您所说的相反,索引是众所周知的.它是在构造函数中出现的索引. MinimumPermissionToEdit 出现在第二个位置,因此其索引为1.

In that case, there is no way to get the value by name. You just have to use the index. Contrary to what you say, the index is well known. It is the index it occurs in the constructor. MinimumPermissionToEdit occurs at the second position, so its index is 1.

这篇关于如何使用.NET获取属性中的构造函数参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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