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

后端 未结 4 1704
南方客
南方客 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 21:49

    No, not all objects have a Name property (for starters).

    But you can store objects of interest in a Dictionary<string, object>. You could also get a Control by name, the exact method would depend on the UI library.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-06 22:07

    Well I think what you are looking for is Reflection.

    You can see a good example here: http://www.switchonthecode.com/tutorials/csharp-tutorial-using-reflection-to-get-object-information

    As said before - objects don't have names but you can traverse the objects and get their type and act accordingly.

    This blog here shows a real good example of traversing and usage of reflection.

    This should be a good start for sure. Enjoy!

    0 讨论(0)
  • 2020-12-06 22:08

    No, it's not.

    Objects don't have names - variables do. An object may be referenced by any number of variables: zero, one or many.

    What you can do, however, is get fields (static or instance variables) by name (using Type.GetField) and get the values of those fields (for a specific instance, if you're using instance variables).

    Depending on what you're trying to do, you might also want to consider a dictionary from names to objects.

    0 讨论(0)
提交回复
热议问题