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

标签 c# attributes filehelpers

<分区>

我正在使用 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 方法中访问自定义属性值。

我如何实现这一目标?

最佳答案

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

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

关于c# - 如何获取字段的自定义属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18201971/

相关文章:

特定类的 C# AttributeUsage

Python OOP 实例和类的可变性

c# - 使用 FileHelper 格式化属性

c# - 如何在C#中创建声谱图?

c# - 错误4无效的表达词 'else'

c# - 使用 Office 应用程序简单查询数据库?

c# - 使用FileHelperAsyncEngine崩溃无一异常(exception)

C# - 从 RichTextBox 和 TextBox 添加两个数字

javascript - 使用 JavaScript 获取输入字段的 Id

c# - FileHelpers - 'FieldConverter' 在此声明类型上无效