This article describes the operation of C# obtaining and setting object attribute value through attribute name strings. It is shared with you for your reference, as follows:
#Get object attribute value through reflection and set attribute value
0. Define a class
public class User { public int Id { get; set; } public string Name { get; set; } public string Age { get; set; } }
1. Obtain the object attribute value through the attribute name (string)
User u = new User(); = "lily"; var propName = "Name"; var propNameVal = ().GetProperty(propName).GetValue(u, null); (propNameVal);// "lily"
2. Set object attribute value through attribute name (string)
User u = new User(); = "lily"; var propName = "Name"; var newVal = "MeiMei"; ().GetProperty(propName).SetValue(u, newVal); (propNameVal);// "MeiMei"
#Get all attribute names and types of objects
Implementation through class objects
User u = new User(); foreach (var item in ().GetProperties()) { ($"propName:{},propType:{}"); } // propName: Id,propType: Int32 // propName:Name,propType: String // propName:Age,propType: String
Implemented by class
foreach (var item in typeof(User).GetProperties()) { ($"propName:{},propType:{}"); } // propName: Id,propType: Int32 // propName:Name,propType: String // propName:Age,propType: String
#Determine whether an object contains a certain attribute
static void Main(string[] args) { User u = new User(); bool isContain= ContainProperty(u,"Name");// true } public static bool ContainProperty( object instance, string propertyName) { if (instance != null && !(propertyName)) { PropertyInfo _findedPropertyInfo = ().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; }
Encapsulate it as an extension method
public static class ExtendLibrary { /// <summary> /// Use reflection to determine whether an object contains a certain attribute /// </summary> /// <param name="instance">object</param> /// <param name="propertyName">Properties that need to be judged</param> /// <returns> Whether to include</returns> public static bool ContainProperty(this object instance, string propertyName) { if (instance != null && !(propertyName)) { PropertyInfo _findedPropertyInfo = ().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; } } static void Main(string[] args) { User u = new User(); bool isContain= ("Name");// true }
For more information about C# related content, please check out the topic of this site:C# data structure and algorithm tutorial》、《Summary of C# traversal algorithm and skills》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial》
I hope this article will be helpful to everyone's C# programming.