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

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

i.e. get this.obj0 using

string objectName = "obj0";
executeSomeFunctionOnObject(this.someLoadObjectByName(objectName));
+3
source share
4 answers

No, it is not.

Objects have no names - variables do. An object can refer to any number of variables: zero, one or many.

However, you can get the fields (static or instance variables) by name (using Type.GetField) and get the values ​​from these fields (for a specific instance, if you use instance variables).

Depending on what you are trying to do, you may also consider a dictionary from names to objects.

+8
source

, Name ( ).

, , Dictionary<string, object>. , .

+1

. , , ( , ). , , :

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

PropertyInfo[] myproperties = myType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

GetField GetProperty ( ) , , ( null).

:

GetProperty

GetProperties

GetField

GetField

0

Well, I think you're looking for Reflection.

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

As already mentioned, objects have no names, but you can move objects and get their type and act accordingly.

This blog here shows a real good example of going through and using reflection.

This should be a good start. Enjoy it!

0
source

Source: https://habr.com/ru/post/1726923/


All Articles