简体   繁体   English

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

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

I have a series of C# static lists in an API project that are very similar to the simple example defined here.我在 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",},         
    };
  }
}

These models establish a common information reference between a Javascript web application and the API that services the application.这些模型在 Javascript web 应用程序和为该应用程序服务的 API 之间建立了公共信息参考。

User's are uploading spreadsheet data to the API that includes the list class name and the Title of an item in the list.用户正在将电子表格数据上传到 API,其中包括列表 class 名称和列表中项目的标题。 I need to be able to determine what Id is associated with the Title - if any.我需要能够确定与标题相关联的 Id - 如果有的话。

For example I know that this the information is in the list CommonSelectOptionsYesNo.Table and the Title property is "Yes".例如,我知道该信息位于 CommonSelectOptionsYesNo.Table 列表中,并且 Title 属性为“是”。 I can therefore determine that the the Id is 1.因此,我可以确定 Id 为 1。

In principle I can set up a switch / case method that picks the list identified as CommonSelectOptionsYesNo.Table and then gets the Id value.原则上,我可以设置一个 switch / case 方法,该方法选择标识为 CommonSelectOptionsYesNo.Table 的列表,然后获取 Id 值。 There are however than 60 of these reference lists and they keep growing.然而,这些参考列表中有 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? 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?

After further research have worked out the following method to call up the static readonly list and return the Id for any given "Title" value.经过进一步研究,制定了以下方法来调用 static 只读列表并返回任何给定“标题”值的 Id。

The propModelKey is stored with the static list class in a dictionary of all the lists. propModelKey 与 static 列表 class 一起存储在所有列表的字典中。

The list can be extracted as an object - knowing that the list is always declared with the property name "Table".该列表可以提取为 object - 知道该列表始终使用属性名称“Table”声明。

The properties of the list objects can vary depending on the purpose of the list but they always have the "Id" and "Title" properties.列表对象的属性可以根据列表的用途而有所不同,但它们始终具有“Id”和“Title”属性。 Serializing and deserializing the object with the simple class object "SelectOptions" generates a list that can be queried to extract the Id corresponding to the Title string submitted.使用简单的 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