lundi 10 juin 2019

How do I get the name of a parameter passed to my function?

(Sorry if this is a duplicate, but I've been doing a lot of searching and haven't found an answer)

I'm currently working on a object save/load system that allows me to save data between sessions, namely settings and the like. My current 'saver' requires me to input a string for the name of the setting, which isn't too much work. However, I'm starting to expand the system, and I'm going to be saving tens if not hundreds of objects (not often though). Now, having to pass the name as a parameter is very tricky now, because I'm using for loops, so unless I want to create a new list for the names, I need a better method.

I've tried many different solutions:
obj.GetType().Name, which simply outputs the Type name
nameof(obj), which outputs "obj" and even

public static string GetName<T>(Expression<Func<T>> expr)
    {
        MemberExpression body = ((MemberExpression)expr.Body);
        string name = body.Member.Name;
        //object value = ((FieldInfo)body.Member).GetValue(((ConstantExpression)body.Expression).Value);
        return name;
    }
    GetName(() => obj)

which gives me "obj" as well.
I haven't tried ref obj yet, but I'm assuming that will be the same. Any help is much appreciated.





Aucun commentaire:

Enregistrer un commentaire