【问题标题】:Is it possible to find object in class by name?是否可以按名称在类中找到对象?
【发布时间】:2020-09-06 19:34:16
【问题描述】:

Item.cs

public class Item
{
    public int itemId;
    public string itemName;
    public string itemDescription;
    public string itemType;
}

Food.cs

public class Food
{
    public Item Apple;
    public Item Plum;
}

我正在尝试这个:

Food food = getFood();
string wantedObj = getObjName();

print(food." wantedObj ".itemDescription);

那么有可能做这样的事情吗?我不知道wantedObj,可能是ApplePlum,所以我们需要获取信息取决于wantedObj 字符串。

我不知道如何通过对象名称查找类对象。

【问题讨论】:

  • 不确定这里的最终目标是什么
  • Food没有有属性“Apple”和“Plum”但是有一个Dictionary<string,Item>,其中“wantedObj”是关键。
  • 我觉得您应该改用多态性。这是一个 XY 问题;您正在尝试解决一些问题并提出了这个不起作用的糟糕解决方案,所以您现在要求我们修复您损坏的解决方案.. 我们应该做的是帮助您找到更好的解决方案,并且把这个扔掉。告诉我们更多关于您的实际问题
  • 这能回答你的问题吗? Finding the Concrete Type behind an Interface instance我认为第二个答案是正确的。

标签: c#


【解决方案1】:

考虑下面的代码,没有反射:


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

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多