【问题标题】:How do I get the custom attribute value of a field? [duplicate]如何获取字段的自定义属性值? [复制]
【发布时间】:2013-08-13 06:18:46
【问题描述】:

我正在使用 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**

        }
    }
}

如上所示,我想在属性的 set 方法中访问自定义属性值。

我如何做到这一点?

【问题讨论】:

标签: c# attributes filehelpers


【解决方案1】:

您可以使用反射来做到这一点。

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);
            }
        }
    }
}

更多信息请参考this

【讨论】:

    【解决方案2】:

    这样做的唯一方法是使用反射:

    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”不包含“长度”的定义
    • @vijay 当然,我已经创建了自己的属性类,具有Length 属性。您必须调整代码以反映您的属性类结构。
    • 谢谢,FieldFixedLengthAttribute 是在 FileHelpers 库中定义的。我只使用dll。最后删除“长度”正在工作: var length = ((FieldFixedLengthAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof (FieldFixedLengthAttribute)));但是在鼠标悬停时,我可以看到 FieldFixedLengthAttribute 类型已经公开了名为“Length”的属性,this is the screenshot link。我查看了 FileHelpers lib 源代码,发现“Length”属性被声明为内部的。有没有办法从中提取价值?
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2013-05-30
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    相关资源
    最近更新 更多