How to access class member line by line in C #?

Is there a way to access a member by string (which is the name)?

eg. if static code:

classA.x = someFunction(classB.y); 

but I have only two lines:

 string x = "x"; string y = "y"; 

I know that in JavaScript you can simply:

 classA[x] = someFunction(classB[y]); 

But how to do it in C #?

Also, is it possible to determine the name from a string?

For instance:

 string x = "xxx"; class{ bool x {get;set} => means bool xxx {get;set}, since x is a string } 

UPDATE , to tvanfosson, I can't get it to work, this is:

 public class classA { public string A { get; set; } } public class classB { public int B { get; set; } } var propertyB = classB.GetType().GetProperty("B"); var propertyA = classA.GetType().GetProperty("A"); propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB, null) as string ), null ); 
+6
source share
1 answer

You need to use reflection .

  var propertyB = classB.GetType().GetProperty(y); var propertyA = classA.GetType().GetProperty(x); propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB,null) as Foo ), null ); 

where Foo is the type of parameter that someFunction requires. Note that if someFunction takes an object , you do not need a throw. If the type is a value type, you need to use (Foo)propertyB.GetValue(classB,null) to use it.

I assume that we are working with properties, not fields. If this is not the case, you can change the use of methods for fields instead of properties, but you should probably switch to using properties, and fields should usually not be public.

If the types are incompatible, i.e. someFunction does not return property type A or is not assigned, then you need to do the conversion to the desired type. Similarly, if type B is not compatible with the function parameter, you will need to do the same.

  propetyA.SetValue( classA, someFunction(Convert.ToInt32( propertyB.GetValue(classB,null))).ToString() ); 
+10
source

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


All Articles