简体   繁体   中英

C# : using a variable when being passed it's string name

so if the string name of a variable is passed into a method, I know which variable to use.

in the following example, the area I need help with is PrintVar(string)...turning the string argument into the variable...so that it prints out "here be variable 1" and "here be variable 2" respectively...Thanks!


class ReflectionTest
{    
    class MyObj
    {
        private string myvar;

        public MyObj(string input)
        {   this.myvar = input; }

        public override string ToString()
        {   return ("here be " + myvar);    }   
    }

    class MyClass
    {
        private MyObj var1;
        private MyObj var2;

        public MyClass()
        {   
            var1 = new MyObj("variable 1");
            var2 = new MyObj("variable 2");
        }

        public void PrintVar(string theVariable)
        { 
            Console.WriteLine(theVariable); 
        }   
    }


    static void Main()
    {
        MyClass test = new MyClass();
        test.PrintVar("var1");
        test.PrintVar("var2");
    }
}

If you need to fetch things by name, then personally I'd start by using a dictionary in the internal implementation, ie

private readonly Dictionary<string,MyObj> fields =new Dictionary<string,MyObj>();

public MyClass()
{
    fields["var1"] = new MyObj("variable 1");
    fields["var2"] = new MyObj("variable 2");
}
public void PrintVar(string fieldName)
{
    Console.WriteLine(fields[fieldName]);
}

The other option would be reflection ( GetType().GetFields() ):

public void PrintVar(string fieldName)
{
    Console.WriteLine(GetType().GetField(fieldName,
        BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM