lundi 23 septembre 2019

Get nameof() passed parametr inside method

I am searching for solution for my project, where I have Dictionary(string, object) and helper method witch is trying to get some specific value from dictionary.

As you can see below, if I don't have stringKey, I am trying to get that stringKey from @object, (now it will return "object". Surely, I can do it in calling, but it looks too bad for me.

Is there any way to do that in this method?

public static bool GetValue<T>(Dictionary<string, object> dict, ref T @object, string stringKey = "")
        {
            if (string.IsNullOrEmpty(stringKey))
            {
               stringKey = nameof(@object);
            }
            dict.TryGetValue(stringKey, out var Object);
            if (Object != null)
            {
                @object = (T)Object;
                return true;
            }
            return false;
        }

Example of calling:

DPH.GetValue(dictParam, ref Browser);

Expectations in method is that stringKey will be "Browser", as it will be in this case:

DPH.GetValue(dictParam, ref Browser, nameof(Browser));

There are specific needs and we are not able to refactor that Dictionary to our object or our class at this moment, calling with nameof() is possible, but not a solution.

Thank you for you time!





Aucun commentaire:

Enregistrer un commentaire