C# 如何将GetField()的结果转换为可用对象?
在下面的代码中,类C# 如何将GetField()的结果转换为可用对象?,c#,reflection,unity3d,C#,Reflection,Unity3d,在下面的代码中,类ButtonScript有一个名为buttonObj的字段,其类型为GameObject var button = gameObject.AddComponent<ButtonScript>(); var obj = button.GetType().GetField("buttonObj"); Debug.Log(obj); //prints UnityEngine.GameObject Debug.Log(obj.name); //compilation er
ButtonScript
有一个名为buttonObj
的字段,其类型为GameObject
var button = gameObject.AddComponent<ButtonScript>();
var obj = button.GetType().GetField("buttonObj");
Debug.Log(obj); //prints UnityEngine.GameObject
Debug.Log(obj.name); //compilation error
为什么它在登录时说它是GameObject
,而在我尝试使用它时说它是FieldInfo
对象
如何获取它,以便将其视为
GameObject
?obj变量的类型是FieldInfo
,而不是GameObject
FieldInfo
类表示有关buttonObj
字段的元数据信息。它不包含其值
要获得它的值,必须使用如下的GetValue
方法:
var button = gameObject.AddComponent<ButtonScript>();
var field = button.GetType().GetField("buttonObj");
//Assuming that the type of the field is GameObject
var obj = (GameObject)field.GetValue(button);
var name = obj.name;
var-button=gameObject.AddComponent();
var field=button.GetType().GetField(“buttonObj”);
//假设场的类型是GameObject
var obj=(游戏对象)field.GetValue(按钮);
var name=obj.name;
FieldInfo
的ToString
很可能返回该字符串。这是一个简单的打字错误吗?属性名称是name
,而不是name
@YacoubMassad no,小写的name
是正确的
var button = gameObject.AddComponent<ButtonScript>();
var field = button.GetType().GetField("buttonObj");
//Assuming that the type of the field is GameObject
var obj = (GameObject)field.GetValue(button);
var name = obj.name;