gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:52 25 4
gpt4 key购买 nike

我创建了这个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com