C
C#6d ago
sashok

Unable to get the FieldInfo's value

public static List<T> FindInstances<T>(object value)
{
List<T> instances = new();

Type type = value.GetType();

foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);

if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}

return instances;
}
public static List<T> FindInstances<T>(object value)
{
List<T> instances = new();

Type type = value.GetType();

foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);

if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}

return instances;
}
The following method should find the fields of type T in the class. When having these strings, it only returns a List of 2 empty ones.
public string string1 = "string 1";
public string string2 = "string 2";
public string string1 = "string 1";
public string string2 = "string 2";
5 Replies
Doombox
Doombox6d ago
foreach (var inst in FindInstances<string>(new FooBar()))
{
WriteLine(inst);
}

static List<T> FindInstances<T>(object value)
{
List<T> instances = new();

Type type = value.GetType();

foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);

if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}

return instances;
}

class FooBar
{
public string foo = "foo";
public string bar = "bar";
}
foreach (var inst in FindInstances<string>(new FooBar()))
{
WriteLine(inst);
}

static List<T> FindInstances<T>(object value)
{
List<T> instances = new();

Type type = value.GetType();

foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);

if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}

return instances;
}

class FooBar
{
public string foo = "foo";
public string bar = "bar";
}
No description
Doombox
Doombox6d ago
very much a "works on my machine" moment
sashok
sashok6d ago
Just run it in a console app and this works fine there. Seems like a Unity problem, since that's where I initially run it.
Doombox
Doombox6d ago
might have to use type.GetFields(BindingFlags.Instance | BindingFlags.Public) but I'm not 100%, I try to avoid reflection in Unity but if you know for sure it's a Unity problem it might be a bit easier to find a solution with google at least
sashok
sashok6d ago
The fields are found properly, and the value's type is checked properly too, it's just that GetValue returns the empty string in Unity. I'll try to research this thing. Thank you a lot for your help!