Attribute Reading Problem in C #

1

I have the following problem, I have my ENUM class:

public enum DataBaseType
{
    DATA_BASE_NAME, SERVER_IP_NAME, PORT, USER_NAME, PASSWORD
};

I have my Attributes, in which you have this ENUM:

 public class Connect : System.Attribute
{
    public DataBaseType ValueType { get; set; }
}

I have my Connection class, being:

class ConnectionModel
{
    [Connect(ValueType = DataBaseType.SERVER_IP_NAME)]
    string ServerName { get; set; } = "localhost";
    [Connect(ValueType = DataBaseType.PORT)]
    string Port { get; set; } = "5432";
    [Connect(ValueType = DataBaseType.USER_NAME)]
    string UserName { get; set; } = "usuario";
    [Connect(ValueType = DataBaseType.PASSWORD)]
    string Password { get; set; } = "senha";
    [Connect(ValueType = DataBaseType.DATA_BASE_NAME)]
    string DatabaseName { get; set; } = "banco";
}

I also read this class:

Type type = obj.GetType();
        foreach (FieldInfo field in type.GetRuntimeFields())
        {
            Console.WriteLine(field.Name + ": " + field.GetValue(obj));
        }

So far everything is working, but now I need to know which ValueType was determined for each variable, so I do the following:

Type type = obj.GetType();
        foreach (FieldInfo field in type.GetRuntimeFields())
        {
            Console.WriteLine(field.Name + ": " + field.GetValue(obj));
            Connect attribute = field.GetCustomAttribute<Connect>();
            if (attribute != null)
            {
                MessageBox.Show("Is Not Null: " + attribute.ValueType);
            }
        }

The problem is: Every time the attribute is giving null, why does it load that? Where am I going wrong?

    
asked by anonymous 21.08.2018 / 23:07

1 answer

0

The code to retrieve atributos of a property is done by retrieving its properties and in each property fetch its attribute (by method GetCustomAttribute ), example :

ConnectionModel obj = new ConnectionModel();
Type type = obj.GetType();
foreach (PropertyInfo field in type.GetProperties())
{
    Console.WriteLine(field.Name + ": " + field.GetValue(obj));
    Connect attribute = field.GetCustomAttribute<Connect>();
    if (attribute != null)
    {
        Console.WriteLine(attribute.ValueType);
    }
}

In this case the code will work with the properties being set as the public modifier, if they are not set to public , they will be internal so you need to set type.GetProperties settings to have this visibility, example :

type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))

OnLine Example

21.08.2018 / 23:19