首页 > 解决方案 > c#使用没有反射的列表访问类的特定成员

问题描述

我想检查一个类的特定字段的内容。如果没有值,它应该给出一个消息。当前示例正在运行。但我正在寻找一种没有反射的方法。

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;
   }
}

有没有办法做到这一点:

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

我正在寻找一种没有刺痛的工作解决方案。使用字符串会给重构带来麻烦,如果出错,它会在运行时崩溃。

标签: c#reflectionmember

解决方案


推荐阅读