c# - 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};
我正在寻找一种没有刺痛的工作解决方案。使用字符串会给重构带来麻烦,如果出错,它会在运行时崩溃。
解决方案
推荐阅读
- javascript - 内容在页面加载几秒钟后出现
- python-3.x - 从上面的文件夹导入python文件时出现问题
- gitlab - 我如何在 2020 年离开 GitLab 项目/组
- c++ - C++ 枚举类作为可变模板参数
- sql - 如何使用 DML 命令从两个不同的表中更新表中的列
- c++ - 错误:我的班级的“操作员>>”不匹配
- vb.net - 从文本中读取文件并创建循环
- tensorflow - 如何使用 TensorFlow 2 自定义 CNN 层,在 CNN 的密集层提供新输入
- javascript - 未捕获的类型错误:无法读取创建的 VueJ 中未定义的属性“0”
- php - 用户提交收据后删除购物车中的项目