dimanche 14 mars 2021

c# Accessing specific members of a class with a list without Reflection

I want to check specific fields of a class for content. If there is no value, it should give a message. The current example is working. But I am looking for a way to to the same without Reflection.

using System;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
       static void Main(string[] args)
       {
           TableDescription table1 = new TableDescription { BUYER_AID = 0, DESCRIPTION_LONG = 3, EAN = 2, SUPPLIER = 17};
           TableDescription table2 = new TableDescription();
           string [] members = new string[] { "BUYER_AID", "DESCRIPTION_LONG", "EAN" };
           CheckAndSetValue(table1, table2, members);
       }

       static void CheckAndSetValue(TableDescription t1, TableDescription t2, string[] list)
       {
           foreach (string name in list)
           {
               Type type = typeof(TableDescription);
               FieldInfo typeinfo = type.GetField(name);
               short value = Convert.ToInt16(typeinfo.GetValue(t1));
               if (0 != value)
               {
                   typeinfo.SetValue(t2, value);
               }
               else
               { 
                    Console.WriteLine($"Value for {name} is missing!");
               }
           }
       }
   }
   public class TableDescription
   {
       public short BUYER_AID = 0;
       public short DESCRIPTION_LONG = 0;
       public short EAN = 0;
       public short SUPPLIER = 0;
   }
}

Is there a way to to it something like:

var[] members = new var[]{TableDescription.BUYER_AID, TableDescription.DESCRIPTION_LONG, TableDescription.EAN};

I am looking for a solution to work without stings. Working with Strings will make trouble with refactoring and on error it will crash during runtime.





Aucun commentaire:

Enregistrer un commentaire