[英]Dynamically casting objects from FieldInfo.GetValue in c#
I'm trying to iterate through all the fields in an instance of a class and extract their name / data.我正在尝试遍历 class 实例中的所有字段并提取它们的名称/数据。 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.但是,我必须在字段中手动检查 object 的类型,然后将其转换为该类型的新实例以访问 Value 成员。 This is annoying as every time I add a new data type to the CentralParams class I will have to handle it explicitly here.
这很烦人,因为每次我向 CentralParams class 添加新数据类型时,我都必须在这里明确处理它。
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. v.GetValue(_centralParams).GetType()
返回我需要的类型,所以看起来应该是可能的。
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 .从 C# 8.0 开始,您可以使用模式匹配。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.