How do I reference a field in Linq based on a dynamic fieldname

后端 未结 5 1330
予麋鹿
予麋鹿 2021-01-05 08:22

Firstly, apologies for the bad question title - not entirely sure if I am asking the correct thing.

Normally I can do the following to access a field:



        
5条回答
  •  时光说笑
    2021-01-05 08:43

    In order to do this, you will need to use reflection.

    public object GetField(object obj, string fieldName) { 
      var t = obj.GetType();
      var field = t.GetField(fieldName);
      return field.GetValue(obj);
    }
    
    somevalue = GetField(table, "someFieldName");
    

    This works as long as the field is both instance and public. You'd need to modify the GetField method call slightly if the accessibility was less than public.

提交回复
热议问题