All in comments.
/// <Summary>
/// Convert datareader to generic
/// </Summary>
/// <Typeparam name = "T"> input object class </typeparam>
/// <Param name = "objreader"> datareader object </param>
/// <Returns> </returns>
Public static ilist <t> readertolist <t> (this idatareader objreader)
{
Using (objreader)
{
List <t> List = new list <t> ();
// Obtain the input data type
Type modeltype = typeof (t );
// Traverse the datareader object
While (objreader. Read ())
{
// Use the constructor with the highest matching value with the specified parameter to create an instance of the specified type
T model = activator. createinstance <t> ();
For (INT I = 0; I <objreader. fieldcount; I ++)
{
// Determine whether the field value is null or does not exist
If (! Isnullordbnull (objreader [I])
{
// Match the field name
Propertyinfo Pi = modeltype. getproperty (objreader. getname (I), bindingflags. getproperty | bindingflags. Public | bindingflags. instance | bindingflags. ignorecase );
If (Pi! = NULL)
{
// Bind a field with the same name in the object
Pi. setvalue (model, checktype (objreader [I], Pi. propertytype), null );
}
}
}
List. Add (model );
}
Return list;
}
}
/// <Summary>
/// Convert the null type (* otherwise, an error is reported)
/// </Summary>
/// <Param name = "value"> value of the datareader field </param>
/// <Param name = "conversiontype"> type of the field </param>
/// <Returns> </returns>
Private Static object checktype (object value, type conversiontype)
{
If (conversiontype. isgenerictype & conversiontype. getgenerictypedefinition (). Equals (typeof (nullable <> )))
{
If (value = NULL)
Return NULL;
System. componentmodel. nullableconverter = new system. componentmodel. nullableconverter (conversiontype );
Conversiontype = nullableconverter. underlyingtype;
}
Return convert. changetype (value, conversiontype );
}
/// <Summary>
/// Determine whether the specified object is a valid value
/// </Summary>
/// <Param name = "OBJ"> </param>
/// <Returns> </returns>
Private Static bool isnullordbnull (Object OBJ)
{
Return (OBJ = NULL | (obj is dbnull ))? True: false;
}
/// <Summary>
/// Model conversion for datareader
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "objreader"> </param>
/// <Returns> </returns>
Public static t readertomodel <t> (this idatareader objreader)
{
Using (objreader)
{
If (objreader. Read ())
{
Type modeltype = typeof (t );
Int COUNT = objreader. fieldcount;
T model = activator. createinstance <t> ();
For (INT I = 0; I <count; I ++)
{
If (! Isnullordbnull (objreader [I])
{
Propertyinfo Pi = modeltype. getproperty (objreader. getname (I), bindingflags. getproperty | bindingflags. Public | bindingflags. instance | bindingflags. ignorecase );
If (Pi! = NULL)
{
Pi. setvalue (model, checktype (objreader [I], Pi. propertytype), null );
}
}
}
Return Model;
}
}
Return default (t );
}