Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the custom attribute value of a field? [duplicate]

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.

How do I achieve this?

like image 378
vijay Avatar asked Aug 13 '13 06:08

vijay


2 Answers

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

for more information please refer this

like image 174
3 revs, 2 users 93% Avatar answered Oct 07 '22 16:10

3 revs, 2 users 93%


The only way of doing this is using the reflection:

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

I've tested it with following FieldFixedLengthAttribute implementation:

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

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

You have to adapt the code to reflect properties of your attribute class.

like image 22
MarcinJuraszek Avatar answered Oct 07 '22 16:10

MarcinJuraszek