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

2020-02-06 10:18发布

问题:

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

i.e. get this.obj0 using

string objectName = "obj0";
executeSomeFunctionOnObject(this.someLoadObjectByName(objectName));

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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!