简体   繁体   中英

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. I tried using

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

but props is an empty array. I think typeof isn't working. 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. What is the problem?

Either make your fields properties which have getters and setters:

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:

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:

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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