Is it possible to call members of a Dynamic class as a string?

Asked

Viewed 43 times

0

using System;

public class Program
{
    public static void Main()
    {
        dynamic stud = new Student();
        Console.WriteLine(stud.Name);
        
    }
}

public class Student
{
    public string Name = "John";
}

Output John

Is there any way to get the same result called the member as a string without modifying the class, something like:

Console.WriteLine(stud["Name"]);
  • as doubt in itself would be possible, but not at least Name is a Property, can do it by Reflexion, but being a public member who is not Property can not use the method GetProperty that would solve this easy, need to go deeper into Reflexion to read the variable ... already as code itself is absolutely meaningless to create a dynamic from a known type (Student), something like var stud = new Student() would be best, outside that exposing a public variable is not a good approach, a property would be better there.

  • @Ricardopunctual this was just an illustrative example.

1 answer

1


As a response, not taking into account the code itself, can be done by case Reflexion Name be a property:

var name = stud
          .GetType()
          .GetProperty("Name")  // Só funciona com properties
          .GetValue(stud, null);

In the case of being a variable, another possibility (a gambiarra actually, just to illustrate) would be to use a serializer, such as the Newtonsoft.Json to access as if it were a key from a dictionary:

var serializado =  Newtonsoft.Json.JsonConvert.SerializeObject(stud);
var objeto = Newtonsoft.Json.JsonConvert.DeserializeObject(serializado);
var name = objeto["Name"];

Here are the two working examples: https://dotnetfiddle.net/NAPxlV

Browser other questions tagged

You are not signed in. Login or sign up in order to post.