1

I want to get the value of a desired variable among several variables in a class

When i put string and class in Method, the method returns the value of the variable with the same name as the string received among all variables included in the class.

This method can get any type of class. So this method need to use generic.

Do anyone have a good idea for my problem?

public class A
{
    public int valA_int;
    public string valA_string;
    public float valA_float;
    public long valA_long;
}

public class B
{
    public int valB_int;
    public string valB_string;
    public float valB_float;
    public long valB_long;
}

public static class Method {
    public static object GetvalueFromClass<T>(string varName, T classType) {
        //Find val from class
        return object;
    }
}

public class Program {
    public A aClass;
    public B bClass;
    public void MainProgram() {
        object valA_int = Method.GetvalueFromClass("valA_int", aClass);
        object valB_long = Method.GetvalueFromClass("valB_long", bClass);
    }
}

The concept of method is like this.

please help me to figure out my problem.

Natejin
  • 55
  • 9

2 Answers2

2

your task already defined.

if you use

#{Class}.GetType().GetProperty(#{VariableName}).GetValue(#{DefinedClass}, null);

you can easily get variable from your class with variable name.

it returns variable as object. so you need to convert it

Example code

CLASS YourClass = [A CLASS WHICH IS PRE DEFINED];
object Target = YourClass.GetType().GetProperty("YOUR VARIABLE").GetValue(YourClass , null);
Arphile
  • 841
  • 6
  • 18
0

ok, use reflection to get all the variables in the object, then run through a loop checking them against the string of the property name. From there you should be able to return the value.

So something like

public object FindValByName(string PropName)
{
    PropName = PropName.ToLower();
    var props = this.GetType().GetProperties();

    foreach(var item in props) {
        if(item.Name.ToLower() == PropName) {
            return item.GetValue(this);
        }
    }
}
Slipoch
  • 750
  • 10
  • 23