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;