在获得反射实例时如何包含值?
我正在自动化如何使用[序列化]
属于JSON的类别。
我试图通过反射来获取fieldinfo
,并传递该值以 json ,但失败了。 空的卷发括号是输出的。
问题代码
public static class SerializeHelper
{
public static void SerializeObjectField()
{
var fieldsInfo = GameInfo.Instance.GetType().GetFields(
BindingFlags.Public | BindingFlags.Instance);
foreach (var fieldInfo in fieldsInfo)
{
ToJson(fieldInfo);
}
}
private static void ToJson(FieldInfo fieldInfo)
{
var json = JsonUtility.ToJson(fieldInfo, true);
Debug.Log(json); // Empty curly braces are output
}
}
public class GameInfo : MonoBehaviour
{
// Sigleton Pattern
public Gold gold = new();
public int Gold
{
get => gold.Amount;
set => gold.Amount = value;
}
// ...
}
[Serializable]
public class Gold
{
[SerializeField] private int amount;
public int Amount
{
get => amount;
set => amount = value;
}
}
如果我在不使用反射的情况下手动编写它,则输出很好。
正确的代码
// ...
var json = JsonUtility.ToJson(GameInfo.Instance.gold, true);
Debug.Log(json);
// ...
输出
{
"amount": 43 // Create a button that increments by 1 for every click
}
您可以告诉我我在使用反射时做错了什么吗?
I am automating how to serialize a class with [Serializable]
attribute to Json in Unity.
I tried to get the FieldInfo
by reflection and pass that value to parse it as Json, but it failed. Empty curly braces are output.
Problem Code
public static class SerializeHelper
{
public static void SerializeObjectField()
{
var fieldsInfo = GameInfo.Instance.GetType().GetFields(
BindingFlags.Public | BindingFlags.Instance);
foreach (var fieldInfo in fieldsInfo)
{
ToJson(fieldInfo);
}
}
private static void ToJson(FieldInfo fieldInfo)
{
var json = JsonUtility.ToJson(fieldInfo, true);
Debug.Log(json); // Empty curly braces are output
}
}
public class GameInfo : MonoBehaviour
{
// Sigleton Pattern
public Gold gold = new();
public int Gold
{
get => gold.Amount;
set => gold.Amount = value;
}
// ...
}
[Serializable]
public class Gold
{
[SerializeField] private int amount;
public int Amount
{
get => amount;
set => amount = value;
}
}
If I write it manually without using reflection, it outputs just fine.
Correct Code
// ...
var json = JsonUtility.ToJson(GameInfo.Instance.gold, true);
Debug.Log(json);
// ...
Output
{
"amount": 43 // Create a button that increments by 1 for every click
}
Can you please tell me what I am doing wrong when using reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少一个呼叫,属性信息为您提供了字段/属性的描述,该字段/属性与类定义有关,但没有提及您的实际实例。
要实际获取属性信息上需要调用getValue方法的值,
请尝试替换
类似的内容:
下面的工作示例:
You are missing one call, property info gives you a description of a field/property, which is related to class definition but has no reference to your actual instance.
To actually get the value you need to call GetValue method on the property info
try replacing
with something similar to:
A working example below: