C #: getting value through reflection

I would like to know if it is possible to do something like this:

class brand
{
  string name;
}

class car
{
   string carname;
   brand carbrand;
}

now I have such a line and an instance of an object such as a car:

 car carobject = new car();
 string brandNameOfCar = DoSomeMagicalReflectionStuff(car, "car.brand.name");

What does the DoSomeMagicalReflectionStuff method look like?

And it’s even possible to do something like:

 car carobject = new car();
 string brandNameOfCar = DoSomeMagicalReflectionStuff(car, "car.brand.name.ToFormatedString()");

Thanks!

+5
source share
4 answers

Usually I don’t try to connect the products I'm involved in, but this is the ideal problem that needs to be solved, Vici Parser (open expression parser for .NET):

var parser = new CSharpParser();
var context = new CSharpContext();

context["car"] = carobject;

string brandNameOfCar = 
          parser.Evaluate<string>("car.brand.name.ToFormatedString()", context);
+1
source

I have not tested this, but here is something that should work:

car c = new car();
object val = typeof(car).GetField("carbrand", BindingFlags.Private).GetValue(c);
string result = (val as brand).ToFormattedString();
+4
source

Typeof (car).GetProperty( "brand", bindingflags.instance | bindingflags.private).GetValue(carobject, null) . Sry im

edit: ,

0

, - :

class brand
{
    public string name;
}

class car
{

    public car(string s)
    {
        Match match = Regex.Match(s, @"(?<carname>[^\.]+)\.(?<brandname>.+)");
        if (match.Success)
        {
            this.carname = match.Groups["carname"].Value;
            this.carbrand = new brand();
            this.carbrand.name = match.Groups["brandname"].Value;
        } else
        {
            throw new ArgumentException("Not a valid car");
        }
    }

    string carname;
    brand carbrand;

    public override string ToString()
    {
        return carname + "." + carbrand.name;
    }
}

Using:

car c = new car("M5.BMW");
Console.WriteLine(c.ToString());

You can disable it in the Parse and TryParse methods.

0
source

All Articles