mercredi 30 décembre 2015

Method for finding an attribute by string name

I am still very new to C#, (I come from a Python background ).

What I am trying to do is create a function that can return a value in from its object.

Here is what I have so far.

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

What I would ideally like is to call:

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

but I have a feeling I got the wrong end of the stick when reading up on this because I keep getting null reference exceptions.

I do apologise if this is a duplicate question; I have read a lot of other peoples Q&As and I can't seem to make it work for me. Any help, however vague, is much appreciated.





Aucun commentaire:

Enregistrer un commentaire