I'm trying to iterate through all the fields in an instance of a class and extract their name / data. The fields themselves are instances of custom classes for storing data with some specific features I needed. The following works:
foreach (var v in typeof(CentralParams).GetFields())
{
if(v.GetValue(_centralParams).GetType() == typeof(BoolEventProperty))
{
BoolEventProperty prop = (BoolEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
if(v.GetValue(_centralParams).GetType() == typeof(FloatEventProperty))
{
FloatEventProperty prop = (FloatEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
if(v.GetValue(_centralParams).GetType() == typeof(IntEventProperty))
{
IntEventProperty prop = (IntEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
}
However I have to manually check for the type of the object in the field, then cast it to a new instance of that type in order to access the Value member. This is annoying as every time I add a new data type to the CentralParams class I will have to handle it explicitly here.
Is there a way I can dynamically cast it to an empty variable of the correct type?
v.GetValue(_centralParams).GetType()
returns the type I need so seems like it should be possible.
Something along the lines of
var type = v.GetValue(_centralParams).GetType();
var prop = (type)v.GetValue(_centralParams);
Thanks
Starting from C# 8.0 you can use pattern-matching . Something like this:
foreach (var v in typeof(CentralParams).GetFields())
{
var property = v.GetValue(_centralParams);
var value = property switch
{
BoolEventProperty prop => $"{prop.Value} from bool",
FloatEventProperty prop => $"{prop.Value} from float",
IntEventProperty prop => $"{prop.Value} from int",
_ => throw new InvalidOperationException($"Unknown type {property?.GetType()}")
};
print(v.Name + " " + value);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.