C
C#5mo 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
Doombox5mo 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
Doombox5mo ago
very much a "works on my machine" moment
sashok
sashokOP5mo 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
Doombox5mo 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
sashokOP5mo 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!
Want results from more Discord servers?
Add your server