lundi 25 avril 2022

C# Generic method for getting field names based on attributes

I am trying to make a generic method to be used in a lot of places in my code I can make it work with the following code:

public static void GetFieldNames(System.Object obj, List<string> list)
{
    // Getting the class
    Type t = obj.GetType();
    // Getting all the fields(Variables)
    FieldInfo[] fis = t.GetFields(BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public);
    for (int i = 0; i < fis.Length; i++) 
    {
        // Filtering through the list and if the field(Variable) is marked with a ShowInToolTip attribute ....
        ShowInToolTip attribute = Attribute.GetCustomAttribute(fis[i], typeof(ShowInToolTip)) as ShowInToolTip;
        if (attribute != null)
        {
            list.Add(fis[i].Name);
        }
    }
}

But I have to specify which attribute I want the list to add in the method, meaning I have to create a new method every time I want to find different attribute to add.

So I am trying to have the attribute added to the method as a generic Type parameter I have the code below:

public static void GetFieldNames<Att>(System.Object obj, List<string> list) where Att : System.Attribute
{
    // Getting the class
    Type t = obj.GetType();
    // Getting all the fields(Variables)
    FieldInfo[] fis = t.GetFields(BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public);
    for (int i = 0; i < fis.Length; i++) 
    {
        // Filtering through the list and if the field(Variable) is marked with a ShowInToolTip attribute ....
        Att attribute = Attribute.GetCustomAttribute(fis[i], typeof(Att)) as Att;
        if (attribute != null)
        {
            list.Add(fis[i].Name);
        }
    }
}

and I am implementing as follows:

List<string> stats = new List<string>();
CharacterStats characterStats;
GetFieldNames<Stat>(characterStats, stats);

But unfortunately I am getting a null reference error. It is quite late while typing this so I am sure I am making a simple error but if anyone could help just look over the code that would be much appreciated.





Aucun commentaire:

Enregistrer un commentaire