Problem with Reading Attribute in c#

Asked

Viewed 27 times

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 Attributo, 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 have the reading of 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: All the time the attribute is giving null, why do you charge that? where am I missing?

  • i by the hurry forgot that also has a way to recover properties with the Internal modifier, in your case are attributes, but, visibility only in so I made a change in the answer explaining, how can you get around this.

1 answer

0


The code to recover atributos of a property is done by recovering its properties and in each property seeking its attribute (by the 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);
    }
}

then the code will work and the properties are configured as the modifier public, if they have not configured as public, evening internal then you need to put in the type.GetProperties settings to have this visibility, example:

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

Online Example

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.