如何获取字段的自定义属性值?

7

我正在使用FileHelpers编写固定长度文件。

 public class MyFileLayout
{

    [FieldFixedLength(2)]
    private string prefix;

    [FieldFixedLength(12)]
    private string customerName;

    public string CustomerName
    {
        set 
        { 
            this.customerName= value;
            **Here I require to get the customerName's FieldFixedLength attribute value**

        }
    }
}

如上所示,我想在属性的setter方法中访问自定义属性值。 我该如何实现呢?

还有这个,https://dev59.com/LVjUa4cB1Zd3GeqPOijP - Patrick
2个回答

8
您可以使用反射来实现这一点。
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
public class FieldFixedLengthAttribute : Attribute
{
    public int Length { get; set; }
}

public class Person
{
    [FieldFixedLength(Length = 2)]
    public string fileprefix { get; set; }

    [FieldFixedLength(Length = 12)]
    public string customerName { get; set; }
}

public class Test
{
    public static void Main()
    {
        foreach (var prop in typeof(Person).GetProperties())
        {
            var attrs = (FieldFixedLengthAttribute[])prop.GetCustomAttributes
                (typeof(FieldFixedLengthAttribute), false);
            foreach (var attr in attrs)
            {
                Console.WriteLine("{0}: {1}", prop.Name, attr.Length);
            }
        }
    }
}

更多信息请参阅此链接


4
唯一的方法是使用反射:
var fieldInfo = typeof(MyFileLayout).GetField("customerName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
var length = ((FieldFixedLengthAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(FieldFixedLengthAttribute))).Length;

我用以下 FieldFixedLengthAttribute 实现进行了测试:

public class FieldFixedLengthAttribute : Attribute
{
    public int Length { get; private set; }

    public FieldFixedLengthAttribute(int length)
    {
        Length = length;
    }
}

您需要调整代码以反映属性类的属性。


太棒了,谢谢。快结束了,但需要进行一些修复。var length = ((FieldFixedLengthAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof (FieldFixedLengthAttribute))).Length;我收到了这个错误信息:'FileHelpers.FieldFixedLengthAttribute' 不包含 'Length' 的定义。 - vijay
@vijay 当然,我创建了自己的属性类,并带有 Length 属性。您需要调整代码以反映您的属性类结构。 - MarcinJuraszek
谢谢,FieldFixedLengthAttribute是在FileHelpers库中定义的。我只使用dll。删除末尾的“Length”是有效的:var length = ((FieldFixedLengthAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof (FieldFixedLengthAttribute))); 但是当我将鼠标悬停在上面时,我可以看到FieldFixedLengthAttribute类型已经公开了名为“Length”的属性,这是截图链接。我查看了FileHelpers库源代码,并发现“Length”属性被声明为内部属性。有没有办法从中提取值? - vijay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接