'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.
Solution 1:[1]
I was able to achieve the desired outcome by rearranging the method a bit, By removing the object as a parameter and putting in a system type parameter in instead bypassing the need to Type t = obj.GetType();
public static void GetFieldNames<Att>(System.Type t, List<string> list) where Att : System.Attribute
{
// 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 Stat attribute ....
Att attribute = Attribute.GetCustomAttribute(fis[i], typeof(Att)) as Att;
if (attribute != null)
{
list.Add(fis[i].Name);
}
}
}
and then I call it with:
List<string> stats = new List<string>();
GetFieldNames<Stat>(typeof(CharacterStats), stats);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eugene Paul |