我如何获得一个字段的自定义属性值? [英] How do I get the custom attribute value of a field?

查看:98
本文介绍了我如何获得一个字段的自定义属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用FileHelpers写出来的固定长度的文件。

I am using FileHelpers to write out fixed length files.

 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**

        }
    }
}

如上图所示,我想一个访问自定义属性属性的设定方法中值。

As shown above, I would like a access the custom attribute value inside the set method of the property.

我如何做到这一点?

推荐答案

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

You can do this using reflection.

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

有关详细信息,请参阅<一个href=\"http://stackoverflow.com/questions/3925686/retrieve-custom-attribute-parameter-values\">this

for more information please refer this

这篇关于我如何获得一个字段的自定义属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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