Return Enum C #

1

I have the following enum:

 public enum TNFeInfNFeDetImpostoICMSICMS00CST
 {

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("00")]
    item00 = 00,
 }

How do I "get" the value "00" of the enum in question?

I already know that it's usually done like this:

var x = (int)enumQualquer

But it returns "0", only a zero, which is to be expected because of int .

But I need the enum's "00" value.

How do I do it?

    
asked by anonymous 20.09.2016 / 14:33

2 answers

5

You will have to get the XmlEnumAttribute attribute of your enumerator, then read the Name property.

using System;
using System.Linq;
using System.Xml.Serialization;

public enum TNFeInfNFeDetImpostoICMSICMS00CST
{
    [XmlEnumAttribute("00")]
    item00 = 00
}

public static class EnumExtensions
{
    public static T GetCustomAttribute<T>(this Enum enumerador)
    {
        var membro = enumerador.GetType().GetMember(enumerador.ToString()).FirstOrDefault();
        if (membro != null)
        {
            return (T)membro.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        }
        return default(T);
    }
}

public class Program
{
    public static void Main()
    {

        var atributo = TNFeInfNFeDetImpostoICMSICMS00CST.item00.GetCustomAttribute<XmlEnumAttribute>().Name;
        Console.WriteLine(atributo);
    }
}

DotNetFiddle

    
20.09.2016 / 14:55
1

You have to get the attribute that has the text you want. You can use this:

public static class EnumExt {
    public static string GetAttributeDescription(this Enum enumValue) {
        var attributes = enumValue.GetType().GetMember(enumValue.ToString())[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);
        return (attributes.Length > 0) ? ((XmlEnumAttribute)attributes[0]).Name : String.Empty;
    }
}

See running on dotnetFiddle .

I would rethink some things. I'm not sure if this is the case for using an enumeration . Enumerations can not be subject to changes in legislation or actions that you have no control over. This will cause huge maintenance problems. I have experience with this and I can say that you will regret using this in place of a simple table (a dictionary or a specialized type.This data is inherently changeable.

The name already indicates that something is wrong. He was so confused that he had little use. Even if it were the case of an enumeration, the form used seems to be wrong. It looks like it has enumerations inside the enumeration name. The feature seems to be pretty much wrong.

Even if you were to adopt this solution, you would need to do it in a way that makes it more meaningful and easy to organize and manipulate.

Maybe you've already made every system thinking about it. Still, I would reformulate everything. It is a serious conceptual error that will bring so many problems that redoing is already the best solution.

    
20.09.2016 / 15:06