繁体   English   中英

通过反射调用 static class 列表 C#

[英]Invoke a static class list by reflection C#

我在 API 项目中有一系列 C# static 列表,这些列表与此处定义的简单示例非常相似。

using System.Collections.Generic;

namespace myproject.api.PropModels
{
  public class CommonSelectOptionsYesNoItem
  {
        public int Id { get; set; }
        public string Title { get; set; }
  }

  public static class CommonSelectOptionsYesNo
  {
    public static readonly List<CommonSelectOptionsYesNoItem> Table = new List<CommonSelectOptionsYesNoItem>
    {        
          new CommonSelectOptionsYesNoItem { Id = 0, Title = "No",},           
          new CommonSelectOptionsYesNoItem { Id = 1, Title = "Yes",},         
    };
  }
}

这些模型在 Javascript web 应用程序和为该应用程序服务的 API 之间建立了公共信息参考。

用户正在将电子表格数据上传到 API,其中包括列表 class 名称和列表中项目的标题。 我需要能够确定与标题相关联的 Id - 如果有的话。

例如,我知道该信息位于 CommonSelectOptionsYesNo.Table 列表中,并且 Title 属性为“是”。 因此,我可以确定 Id 为 1。

原则上,我可以设置一个 switch / case 方法,该方法选择标识为 CommonSelectOptionsYesNo.Table 的列表,然后获取 Id 值。 然而,这些参考列表中有 60 多个,并且还在不断增长。

Can I use reflection to invoke an instance of the readonly static list based on the the static class object name - in this example CommonSelectOptionsYesNo.Table?

经过进一步研究,制定了以下方法来调用 static 只读列表并返回任何给定“标题”值的 Id。

propModelKey 与 static 列表 class 一起存储在所有列表的字典中。

该列表可以提取为 object - 知道该列表始终使用属性名称“Table”声明。

列表对象的属性可以根据列表的用途而有所不同,但它们始终具有“Id”和“Title”属性。 使用简单的 class object "SelectOptions" 对 object 进行序列化和反序列化,生成一个列表,可以查询该列表以提取与提交的 Title 字符串对应的 Id。

    // This will return an Id of 1 from the simple YesNo list
    var id = GetSelectListIndex("QuestionOneId", "Yes"); 

    // Method to extract the Id of a value in a list given the list model key
    private static int? GetSelectListIndex(string propModelKey, string title)
    {
        if (SelectListModelMap.ContainsKey(propModelKey))
        {
            var model = SelectListModelMap[propModelKey];

            var typeInfo = Type.GetType("myproject.api.PropModels." + model).GetTypeInfo();

            var fieldInfo = typeInfo.DeclaredFields.FirstOrDefault(x => x.Name == "Table");

            var json = JsonConvert.SerializeObject(fieldInfo.GetValue(new object()));

            var dictionary = JsonConvert.DeserializeObject<List<SelectOptions>>(json);

            var index = dictionary.FirstOrDefault(x => x.Title == title)?.Id;

            return index;
        }

        return null;
    }

    // Dictionary of lists with model key and class name
    public static Dictionary<string, string> SelectListModelMap => new Dictionary<string, string>
    {
        { "QuestionOneId", "CommonSelectOptionsYesNo" },
        { "CountryId", "CommonSelectOptionsCountries" },
        // ... other lists
    };

    // generic class to extract the Id / Title pairs
    public class SelectOptions
    {
       public int Id { get; set; }
       public string Title { get; set; }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM