C Programming Method Example for Obtaining Entity Class Attribute Names and Values

  • 2021-12-11 18:43:50
  • OfStack

This article illustrates the method of C # programming to get the name and value of entity class attributes. Share it for your reference, as follows:

Iterate to get all the attribute names of an entity class and the values of all the attributes of the class


// Define first 1 Classes: 
public class User
{
    public string name { get; set; }
    public string gender { get; set; }
    public string age { get; set; }
}
// Instantiate the class and assign values to the properties of the materialized object: 
User u = new User();
u.name = "ahbool";
u.gender = " Male ";
// Output all the property names of this class and the corresponding values of the properties 
Response.Write(getProperties(u));
// The output is : name:ahbool,gender: Male ,age:,
// Traversing to get the properties of the class and the values of the properties: 
public string getProperties<T>(T t)
{
    string tStr = string.Empty;
    if (t == null)
    {
          return tStr;
    }
    System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    if (properties.Length <= 0)
    {
          return tStr;
    }
    foreach (System.Reflection.PropertyInfo item in properties)
    {
          string name = item.Name;
          object value = item.GetValue(t, null);
          if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
          {
                tStr += string.Format("{0}:{1},", name, value);
          }
          else
          {
                getProperties(value);
          }
    }
    return tStr;
}

PS: Here we recommend another C # related tool for your reference:

JSON Online Conversion to C # Entity Class Tool:
http://tools.ofstack.com/code/json2csharp

For more readers interested in C # related content, please check the topics of this site: "C # Data Structure and Algorithm Tutorial", "C # Traversal Algorithm and Skills Summary", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: