简体   繁体   English

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

[英]Get all names of property of another class - Unity 5 C#

I created this class called Genes and I want to get all it's properties inside of another script. 我创建了一个名为Genes的类,并希望将其所有属性都包含在另一个脚本中。 I tried using 我尝试使用

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

but props is an empty array. 但是props是一个空数组。 I think typeof isn't working. 我认为typeof无法正常工作。 This is my class Genes: 这是我班的基因:

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; 
    }
}

and I basically want to run over size, speed, probability and color using a foreach loop. 我基本上想使用foreach循环遍历大小,速度,概率和颜色。 What is the problem? 问题是什么?

Either make your fields properties which have getters and setters: 将您的fields属性设为具有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; 
    }
}

or use GetFields if you really want fields: 或者如果您确实需要字段,请使用GetFields

typeof(Genes).GetFields();

No matter what you chose, these members should furthermore either be public , or you have to use the BindingFlags.NonPublic to look for non-public members: 无论您选择什么,这些成员都应该是public ,或者您必须使用BindingFlags.NonPublic查找非公共成员:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM