使用类名称作为字符串C#设置类变量

时间:2019-06-10 00:37:57

标签: c# .net system.reflection

我试图基于字符串设置类变量的值。我正在查询数据库中的数据,该数据返回一个FieldName,该字段应映射我的类的变量名。

我已经能够获取该类的变量列表,并检查该类变量是否等于返回的FieldName。

但是我无法为此类实例设置值。

任命班:

public class Appointment
{
    public int Id { get; set; }
    public int EmployeeId { get; set; }
    public string EmployeeFullName { get; set; }
    public int SupervisorId { get; set; }
    public string SupervisorFullName { get; set; }
    public string Department { get; set; }
    public int AppointmentType { get; set; }
    public int EmploymentType { get; set; }
}

我在此函数的前面初始化了一个约会类的实例,但是这里是我尝试根据FieldName分配值的代码。

appointment = new Appointment{//Assigned other values based on other query}

using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                SqlCommand command = new SqlCommand(querySelectFields, connection);
                connection.Open();

                BindingFlags bindingFlags = BindingFlags.Public |
                                            BindingFlags.NonPublic |
                                            BindingFlags.Instance |
                                            BindingFlags.Static;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        foreach(FieldInfo field in typeof(Appointment).GetFields(bindingFlags))
                        {
                            // Extracts the field name from original format of "<fieldName>k__BackingField"
                            string tempFieldName = field.Name.Substring(1);
                            string fieldName = tempFieldName.Substring(0, tempFieldName.Length- 16);

                            if ((String)reader["FieldName"] == fieldName)
                            {
                                //This is where it errors
                                field.SetValue(null, int.Parse(reader["SelectValueID"].ToString()));
                            }
                        }
                    }
                }

我得到的错误是:

  

异常详细信息:System.Reflection.TargetException:非静态字段需要一个目标。

我知道这是由于在该调用中将null作为第一个参数而引起的,但是我似乎找不到正确的方法。

理想情况下,我可以执行以下操作:

if((String)reader["FieldName"] == fieldName)
{
    appointment.field = int.Parse(reader["Value"].ToString());
}

那将与:

if((String)reader["FieldName"] == "AppointmentType")
{
    appointment.AppointmentType = int.Parse(reader["Value"].ToString());
}

0 个答案:

没有答案
相关问题