Get field by name

I am trying to create a function that can return a field from its object.

Here is what I still have.

public class Base { public string thing = "Thing"; public T GetAttribute<T>(string _name) { return (T)typeof(T).GetProperty(_name).GetValue(this, null); } } 

Ideally, I would like to call:

 string thingy = GetAttribute<string>("thing"); 

but I have the feeling that I got the wrong end of the stick when I read about it, because I keep getting exceptions for the null reference.

+5
source share
2 answers

First thing is a field, not a property.

Another thing is that you gave a change in the type of parameter to make it work:

 public class Base { public string thing = "Thing"; public T GetAttribute<T> ( string _name ) { return (T)typeof(Base).GetField( _name ).GetValue (this, null); } } 

BTW - you can get the value of a property / field by specifying an instance:

 var instance = new Base(); var value = instance.thing; 
+3
source

thing - a field that is not a property. You should use the GetField method instead of GetProperty . Another problem is that you are looking at typeof(T) . You should look for the field in typeof(Base) .

All function must be changed to

 public T GetAttribute<T>(string _name) { return (T)GetType().GetField(_name).GetValue(this); } 

If you want to have an extension method to get the value of a type field, you can use this

 public static class Ex { public static TFieldType GetFieldValue<TFieldType, TObjectType>(this TObjectType obj, string fieldName) { var fieldInfo = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); return (TFieldType)fieldInfo.GetValue(obj); } } 

Use it like

 var b = new Base(); Console.WriteLine(b.GetFieldValue<string, Base>("thing")); 

Using BindingFlags will help you get the value of a field, even if it is a private or static field.

+5
source

Source: https://habr.com/ru/post/1239498/


All Articles