C#将代码行的一部分更改为变量

C#将代码行的一部分更改为变量,c#,C#,我正在使用Unity3D 我有一个脚本,可以根据生物的某个值对列表进行排序 例如,这些生物有一个变量,表示它们吃了多少食物,目前有多少卡路里,以及它们有多大 我希望用户能够通过单击按钮更改值的排序方式。我不想堆积if语句,比如 if(sortType == "calories") { entrySortedText.text = creatureData.calories.ToString(); } else if(sortType == "food eaten") { entr

我正在使用Unity3D

我有一个脚本,可以根据生物的某个值对列表进行排序

例如,这些生物有一个变量,表示它们吃了多少食物,目前有多少卡路里,以及它们有多大

我希望用户能够通过单击按钮更改值的排序方式。我不想堆积if语句,比如

if(sortType == "calories") {
    entrySortedText.text = creatureData.calories.ToString();
} else if(sortType == "food eaten") {
    entrySortedText.text = creatureData.foodEaten.ToString();
}
我想做一些像这样的事情

entrySortedText.text = creatureData.sortType.ToString();
自动查找名为creatureData中排序类型的变量。但很明显,这不起作用,因为生物数据中没有变量“sortType”,但我希望它能自动用变量名替换sortType,比如“卡路里”或“吃的食物”

有人知道如何将代码行的一部分更改为变量的值吗?还是我只需要使用一堆if语句

谢谢。你的回答很有价值

附言

以下是当前的排序代码:

public void LoadList() {
    foreach(Transform child in transform) {
        GameObject.Destroy(child.gameObject);
    }

    List<GameObject> creatures = new List<GameObject>(GameObject.FindGameObjectsWithTag("Creature").ToList());

    // Sort list based on calories
    creatures.Sort(
        delegate(GameObject i1, GameObject i2) {
            return i2.GetComponent<CreatureData>().calories.CompareTo(i1.GetComponent<CreatureData>().calories);
        }
    );

    foreach(GameObject creature in creatures) {
        GameObject entry = Instantiate(entryPrefab);
        entry.transform.SetParent(transform, false);
        entry.transform.GetChild(0).GetComponent<Text>().text = creature.GetComponent<CreatureData>().creatureName;
        entry.transform.GetChild(1).GetComponent<Text>().text = creature.GetComponent<CreatureData>().calories.ToString();
        entry.GetComponent<CreatureListEntryButton>().targetCreature = creature;
    }
}
public void LoadList(){
foreach(变换中的变换子对象){
GameObject.Destroy(child.GameObject);
}
列表生物=新列表(GameObject.FindGameObjectsWithTag(“生物”).ToList());
//基于卡路里的排序列表
生物,分类(
代理(游戏对象i1、游戏对象i2){
返回i2.GetComponent().carries.CompareTo(i1.GetComponent().carries);
}
);
foreach(生物中的游戏对象生物){
游戏对象入口=实例化(入口预制);
entry.transform.SetParent(transform,false);
entry.transform.GetChild(0.GetComponent().text=bioture.GetComponent().creatureName;
entry.transform.GetChild(1.GetComponent().text=bioter.GetComponent().carries.ToString();
entry.GetComponent().targetBioter=生物;
}
}

所以您希望对属性进行排序,但该属性将在运行时确定。 假设您有一个名为
items
的集合,并且这些项有一个名为
carries
的属性。然后你可以这样做:

var sortBy = "Calories"; 
var propertyInfo = typeof(YourObject).GetProperty(sortBy);  
然后,您可以对其进行排序:

var orderByCalories = items.OrderBy(x => propertyInfo.GetValue(x, null));

你可能在找字典,但我在你发布的代码中没有看到任何排序代码。这不是排序:
creatureData.carries.ToString()如果我不想在运行时设置它怎么办?@rugbugredden好的,奇怪。那你想什么时候设置呢?在某个时刻,你必须做出决定。编译或运行时。还有什么其他选择?@rugbugredfern请参见上述评论。对不起,把你的名字拼错了。