【问题标题】:Accessing values from the string name of a class at runtime在运行时从类的字符串名称访问值
【发布时间】:2015-12-29 04:10:32
【问题描述】:

在我的 C# 类的源代码中,我想使用在某个其他类中定义的参数值。我想在不将其他类名“硬连线”到源代码中的情况下做到这一点(例如,不写“class2.variable”之类的东西)。 相反,我想在运行时将其他类的名称作为字符串传递。

我在 Unity 中使用 C#。所以我想在 Unity 的 Inspector 中将另一个类的名称设置为公共字符串。

例如,考虑以下两个单独的脚本:

using UnityEngine ;
public class ScriptA : ScriptableObject {public static int fred = 5 ;  }

using System;
using System.Reflection; 
using UnityEngine;

public class ScriptB : MonoBehaviour {
    object item;
    private static string instance;

    void Start() {
        instance = "ScriptA";
        item = ScriptableObject.CreateInstance(Type.GetType(instance)); 
        Type myType = item.GetType();

        foreach (FieldInfo info in myType.GetFields())
        {
            string infoName = info.Name; //gets the name of the field
            Debug.Log (" info = " + infoName);  
        }
    } 
}

ScriptB 工作正常;它仅从字符串“instance”访问ScriptA,事实证明 名称“fred”出现在控制台中。

但是我如何访问 "fred" 的值;如何让数字“5”出现在控制台上? 我已经尝试了两天。我已经广泛搜索了答案。 有人可以帮忙吗?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    FieldInfo 有一个GetValue 方法:

    public abstract object GetValue(
        object obj
    )
    

    试试:

    Type myType = item.GetType();
    foreach (FieldInfo info in myType.GetFields())
        {
            string infoName = info.Name; //gets the name of the property
            Console.WriteLine(" Field Name = " + infoName +"and value = "+ info.GetValue(null));  
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多