返回基于类型的对象

本文关键字:对象 类型 于类型 返回 | 更新日期: 2023-09-27 18:19:46

我有5个不同的类,它们都继承自BaseEntity。我想创建一个新的模型类,它将存储关于这5个类中的一个以及其他标识符所需的信息。

当我从数据库中检索这个新模型的数据时,我得到的只是一个具有类类型的字符串和一个整数,该整数表示我可以从数据库中引用哪个条目。

例如,如果检索Id=2,则Type="BaseBall"。这意味着我需要使用BaseBallService来获取Id==2的条目。如果它恰好是Id=2,Type="BasketBall",那么我将使用BasketBallService。

目前,我能想到的唯一解决方案是使用一堆if语句来计算"type"字符串。根据类型是否匹配有效类型(BaseBall、FootBall、BasketBall等),将返回该对象。

有没有一种方法可以轻松地做到这一点,而不需要在模型定义中定义所有5种类型,并串接if或语句来识别这一点?

我希望我已经足够清楚地发现了这个问题。如果需要任何其他信息,请告诉我。我还没有为此编写任何代码。我只是想分析这个问题并形成一个解决方案。

返回基于类型的对象

我只需要在项目或解决方案级别添加一个全局枚举来存储类型。这样,如果您希望以后添加到它中,则可以在分离时不破坏任何现有代码。但这可能会使它保持良好的类型,因此需要最终用户或应用程序列出的类型。我做了一个简单的控制台应用程序来展示这一点。您可以将枚举应用于任何类,而不仅仅是泛型。我还实现了一个返回方法来缩小返回列表的范围,以显示如何更容易地获得列表列表。

public enum types
    {
        Type1,
        Type2,
        Type3
    }
    public class GenericListing
    {
        public string Description { get; set; }
        public types Type { get; set; }
    }
    class Program
    {
        public static List<GenericListing> GetTypeListing(List<GenericListing> aListings, types aTypes)
        {
            return aListings.Where(x => x.Type == aTypes).ToList();
        }
        static void Main(string[] args)
        {
            var stuff = new List<GenericListing>
                {
                    new GenericListing {Description = "I am number 1", Type = types.Type1},
                    new GenericListing {Description = "I am number 2", Type = types.Type2},
                    new GenericListing {Description = "I am number 3", Type = types.Type3},
                    new GenericListing {Description = "I am number 1 again", Type = types.Type1},
                };

            string s = "";
            GetTypeListing(stuff, types.Type1)  // Get a specific type but require a well typed input.
                .ForEach(n => s += n.Description + "'tType: " + n.Type + Environment.NewLine);
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }

您可以尝试使用Dictionary,例如

  Dictionary<String, BaseEntry> types = new Dictionary<String, BaseEntry>() {
    {"BaseBall", new BaseBallService()},
    {"BasketBall", new BasketBallService()},
    ...
  }
  ...
  var value = types["BaseBall"].GetId(2);