dimanche 13 janvier 2019

Get the original name of a variable passed by parameter

I'm trying to get the original name from a variable passed by parameter.

The only thing I saw in Internet was the opposite: "Getting the value from a property based on its name", or using nameof(<some variable here>). And this is what I don't want.

Let see this in pseudo-code:

class A {
   public static string hello;
}
class B {
    public static string GetName<T>(this T obj) {}
}
class C {
    static void Main(string something) {
        Console.WriteLine(something.GetName()); ==> This should return hello, not something
    }
}
class D {
    // call: C.Main(A.hello);
}

As I marked before, I need that the GetName() extension displays in console hello not something.

I tried the following without luck:

using System;
using System.Linq;

namespace Hello.Bye {
    public class Program
    {
        public static string variable {get; private set;}

        public static void Main()
        {
            variable = "Hi!";
            Console.WriteLine(variable.GetVarName());
        }
    }
}

public static class F 
{
        public static string GetVarName<T>(this T input)
            where T : class
        {
            if (input == null)
                return string.Empty;

            var prop = typeof(T).GetProperties().FirstOrDefault(p => p.GetValue(input, null) == input);
            return prop.ReflectedType.FullName + "." + prop.Name;
        }
}

Because the following exception happens:

Run-time exception (line 25): Parameter count mismatch.

Stack Trace:

[System.Reflection.TargetParameterCountException: Parameter count mismatch.] at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at F.<>c__DisplayClass11.<GetVarName>b__0(PropertyInfo p) :line 25 at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func`2 predicate) at F.GetVarName[T](T input) :line 25 at Hello.Bye.Program.Main() :line 12

And this should display: Hello.Bye.variable.

Is right what I'm doing? Or is this impossible to achieve?





Aucun commentaire:

Enregistrer un commentaire