I'm doing some testing with reflection , I made this code on the basis of trial and error, so I did not understand how exactly it works.
This is the enum
I'm using:
public enum TipoDoAmbiente
{
[System.Xml.Serialization.XmlEnumAttribute("1")]
Item1,
[System.Xml.Serialization.XmlEnumAttribute("2")]
Item2,
}
The propriedade.GetValue(objeto, null);
method returns the value of enum
, in case of this test I made the value is item1
. When I do a debug and stop at itemEnum
nothing appears other than the value itself.
I get this value and step into the next methods, my question is how does the rest of the code "discover" the type and information of the member if I am just passing the value item1
?
Type tipo = objeto.GetType();
foreach (PropertyInfo propriedade in tipo.GetRuntimeProperties())
{
Type tipoBase = propriedade.PropertyType.BaseType;
if (tipoBase.Name == "Enum")
{
var itemEnum = propriedade.GetValue(objeto, null);
var valorEnum= (Enum)itemEnum;
var infoEnum = valorEnum.GetType().GetMember(propriedade.GetValue(objeto, null).ToString()).FirstOrDefault();
var EnumAttribute = infoEnum.GetCustomAttribute<XmlEnumAttribute>().Name;
}
}
I'm testing the deserialization of an XML, and I get the object that was generated, that object that is used in the code.
What left me with the most doubt is that there are several enums
with equal values, example item1
.
But just passing item1
to code
var infoEnum = valorEnum.GetType().GetMember(propriedade.GetValue(objeto, null).ToString()).FirstOrDefault();
It returns the class and the property it belongs to.