c# - 获取另一个类的所有属性名称 - Unity 5 C#

标签 c# unity3d

我创建了这个名为 Genes 的类,我想在另一个脚本中获取它的所有属性。我尝试使用

PropertyInfo[] props = typeof(Genes).GetProperties();

但是 props 是一个空数组。我认为 typeof 不起作用。这是我的类基因:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Genes 
{
    private float size;
    private float speed;
    private float probability;
    private int color;

    public Genes(float size, float speed, float probability, int color) 
    {
        this.size = size; 
        this.speed = speed; 
        this.probability = probability; 
        this.color = color; 
    }
}

我基本上想使用 foreach 循环遍历大小、速度、概率和颜色。有什么问题?

最佳答案

要么使您的字段属性具有 getter 和 setter:

public class Genes 
{
    private float Size { get; set; }
    private float Speed { get; set; }
    private float Probability { get; set; }
    private int Color { get; set; }

    public Genes(float size, float speed, float probability, int color) 
    {
        this.Size = size; 
        this.Speed = speed; 
        this.Probability = probability; 
        this.Color = color; 
    }
}

或者如果您确实需要字段,请使用 GetFields:

typeof(Genes).GetFields();

无论您选择什么,这些成员还应该是 public,或者您必须使用 BindingFlags.NonPublic寻找非公开成员:

typeof(Genes).GetProperties(BindingFlags.NonPublic);

typeof(Genes).GetFields(BindingFlags.NonPublic);

关于c# - 获取另一个类的所有属性名称 - Unity 5 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557504/

相关文章:

c# - 将 ContextMenu 命令绑定(bind)到父 View 模型 RelayCommand

c# - 是否使用存储库模式?需要 ORM? MVC 网络 API REST

session - 微软 HoloLens : Mixed Reality 250 - No session available for one HoloLens to join with another HoloLens hosting it

unity3d - 统一 : "The referenced script (Unknown) on this Behaviour is missing!"

c++ - 读取dll文件中的文本文件

c# - 在 Update() 方法中创建新对象

c# - TextFieldParser 从字符串而不是文件解析 CSV

c# - SQL Server 序列间隙

c# - Windows 手机 : Call an Async method in OnNavigatedTo

unity3d - 自定义按钮Unity