C# 是否可以按名称在类中查找对象?
项目1.cs 食品公司C# 是否可以按名称在类中查找对象?,c#,C#,项目1.cs 食品公司 public class Item { public int itemId; public string itemName; public string itemDescription; public string itemType; } 我正在尝试: public class Food { public Item Apple; public Item Plum; } 那么有可能做这样的事情吗?我不知道wantedObj
public class Item
{
public int itemId;
public string itemName;
public string itemDescription;
public string itemType;
}
我正在尝试:
public class Food
{
public Item Apple;
public Item Plum;
}
那么有可能做这样的事情吗?我不知道wantedObj
,它可能是Apple
或Plum
,所以我们需要根据wantedObj
字符串获取信息
我不知道如何按对象名查找类对象。请考虑以下代码,不要进行反射:
Food food = getFood();
string wantedObj = getObjName();
print(food." wantedObj ".itemDescription);
使用制度;
使用System.Collections.Generic;
命名空间TestAPI
{
公共类项目
{
公共int itemId;
公共字符串itemName;
公共字符串项描述;
公共字符串itemType;
}
公共食品
{
公共物品;
公共项目管理;
}
公共课程
{
公共静态字典项选择器=新字典()
{
{“梅花”,f=>f.梅花},
{“苹果”,f=>f.Apple},
};
公共静态void Main(字符串[]args)
{
食品=新食品
{
苹果=新项目()
{
itemId=1,
itemDescription=“苹果”,
itemName=“苹果”
},
梅花=新项目()
{
itemId=2,
itemDescription=“李子”,
itemName=“梅花”
},
};
var wantedObj=“梅花”;
Item wantedItem=项目选择器[wantedObj](食品);
Console.WriteLine(wantedItem.itemName);
}
}
}
不确定这里的最终目标是什么拥有食物
没有“苹果”和“李子”属性,而是一本字典
,其中“wantedObj”是关键。^^^我觉得你应该使用多态性来代替。这是一个XY问题;您试图解决一些问题,但却想出了一个不好的解决方案,因此您现在要求我们修复损坏的解决方案。。实际上,我们应该做的是帮助您找到更好的解决方案,然后扔掉这个解决方案。告诉我们更多关于你的实际问题这是否回答了你的问题?我认为第二个答案是正确的。
using System;
using System.Collections.Generic;
namespace TestAPI
{
public class Item
{
public int itemId;
public string itemName;
public string itemDescription;
public string itemType;
}
public class Food
{
public Item Apple;
public Item Plum;
}
public class Program
{
public static Dictionary<string, Func<Food, Item>> ItemSelectors = new Dictionary<string, Func<Food, Item>>()
{
{"Plum", f => f.Plum },
{"Apple", f => f.Apple },
};
public static void Main(string[] args)
{
Food food = new Food()
{
Apple = new Item()
{
itemId = 1,
itemDescription = "Apple",
itemName = "Apple"
},
Plum = new Item()
{
itemId = 2,
itemDescription = "Plum",
itemName = "Plum"
},
};
var wantedObj = "Plum";
Item wantedItem = ItemSelectors[wantedObj](food);
Console.WriteLine(wantedItem.itemName);
}
}
}