Frage

I can't seem to be able to read a custom enum attribute using the following code:

public class CustomAttribute : Attribute
{
    public CultureAttribute (string value)
{
    Value = value;
}

public string Value { get; private set; }
}

public enum EnumType
{
    [Custom("value1")]
    Value1,
    [Custom("value2")]
    Value2,
    [Custom("value3")]
    Value3
}
...
var memInfo = typeof(CustomAttribute).GetMember(EnumType.Value1.ToString());
// memInfo is always empty
var attributes = memInfo[0].GetCustomAttributes(typeof(CustomAttribute), false);

Not sure if I am just missing something obvious here or if there is an issue with reading custom attributes in Mono/MonoMac.

War es hilfreich?

Lösung

You should call the GetMember() on the type that has the given member of course :) In this case that's EnumType not CustomAttribute. Also fixed what I assume to be copy-paste error with the attribute constructor.

Complete working test code (you should know with 23k reps that we prefer these to half-made programs that we have to complete ourselves ;)):

using System;

public class CustomAttribute : Attribute
{
    public CustomAttribute (string value)
    {
        Value = value;
    }

    public string Value { get; private set; }
}

public enum EnumType
{
    [Custom("value1")]
    Value1,
    [Custom("value2")]
    Value2,
    [Custom("value3")]
    Value3
}

class MainClass
{
    static void Main(string[] args)
    {
        var memInfo = typeof(EnumType).GetMember(EnumType.Value1.ToString());
        Console.WriteLine("memInfo length is {0}", memInfo.Length);
        var attributes = memInfo[0].GetCustomAttributes(typeof(CustomAttribute), false);
        Console.WriteLine("attributes length is {0}", attributes.Length);
    }
}

See in operation.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top