var property = obj. GetType (). GetProperty ("PropertyName");
Represents a property that gets the class obj PropertyName
propertyinfo[] Propertys = T.gettype (). GetProperties ();
Represents getting all the properties of a class T
Traverse all properties of this object
foreach (PropertyInfo pi in Propertys)
{
Tempname = Pi. name;//Assigning a property name to a temporary variable
Check if DataTable contains this column (column name = = Property Name of object)
if (dt. Columns.contains (Tempname))
{
Determine if this property has a setter
if (!pi. CanWrite) continue;//This property is not writable and jumps directly out
Take value
Object value = Dr[tempname];
If not null, the property assigned to the object
if (value! = DBNull.Value)
Pi. SetValue (t, value, NULL);
}
}
The SetValue method is used when assigning values to a class's properties using reflection
This method has 3 parameters, the first represents the class T, the second represents the property value, and the 3rd explains in detail
The property type is a known base type that can be passed directly to the variable, for example: string
var value= "wangheng.org";
Property. SetValue (Obj,value,null);
It is important to note that the type of the value must be the same as the property type, or the targetexception exception will be thrown.
If the original value is a different type. Example: the target type is int and the value is string
String Value= "100″;
Property. SetValue (Obj,int. TryParse (value), null);//Type conversion.
GetValue (Obj,null)