C#: how to get an object by the name stored in String?

后端 未结 4 1764
南方客
南方客 2020-12-06 21:44

is it possible in C# to get an object by name?

i.e. get this.obj0 using

string objectName = \"obj0\";
executeSomeFunctionOnObject(this.someLoadObject         


        
4条回答
  •  眼角桃花
    2020-12-06 22:06

    You can't access an object by name. Using reflection, though, you can all fields and properties of a class (by name, if you want). If your object is stored in a field level variable or in a property, then this will give you what you want:

    Type myType = typeof(MyClass);
    FieldInfo[] myFields = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
    
    PropertyInfo[] myproperties = myType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
    

    You can also call GetField and GetProperty (singular) and pass in a string to have it return a single member matching that name (make sure to check for null).

    Read these pages for more information on reflection methods of use in this situation:

    GetProperty

    GetProperties

    GetField

    GetField

提交回复
热议问题