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

vij*_*jay 3 c# filehelpers attributes

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我该如何实现这一目标?

MST*_*dev 6

你可以使用反射来做到这一点.

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此处


Mar*_*zek 4

执行此操作的唯一方法是使用反射:

var fieldInfo = typeof(MyFileLayout).GetField("customerName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
var length = ((FieldFixedLengthAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(FieldFixedLengthAttribute))).Length;
Run Code Online (Sandbox Code Playgroud)

我已经使用以下FieldFixedLengthAttribute实现对其进行了测试:

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

    public FieldFixedLengthAttribute(int length)
    {
        Length = length;
    }
}
Run Code Online (Sandbox Code Playgroud)

您必须调整代码以反映属性类的属性。