samedi 11 juillet 2020

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.

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.

User's are uploading spreadsheet data to the API that includes the list class name and the Title of an item in the list. I need to be able to determine what Id is associated with the Title - if any.

For example I know that this the information is in the list CommonSelectOptionsYesNo.Table and the Title property is "Yes". I can therefore determine that the the Id is 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. There are however than 60 of these reference lists and they keep growing.

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?





Aucun commentaire:

Enregistrer un commentaire