需要动态的创建一个实例模型的时候,就用Activator.CreateInstance(Type type);
如果是明确的知道要创建哪个实例的模型,就可以用 new Class1()了。
也可以通过程序集Assembly.CreateInstance()来创建,不过其实程序集创建也是调用的Activator.CreateInstance(Type type)。
代码
public static object GetFromDataTable(DataTable dt, Type objectType, int row)
{
if (dt == null)
{
return null;
}
if (dt.Rows.Count <= row)
{
return null;
}
object obj = Activator.CreateInstance(objectType);
PropertyInfo[] props = objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (DataColumn dc in dt.Columns)
{
foreach (PropertyInfo p in props)
{
if (p.Name.Equals(dc.ColumnName, StringComparison.OrdinalIgnoreCase))
{
if (!dt.Rows[row].IsNull(dc.ColumnName))
{
object destObj = dt.Rows[row][dc.ColumnName];
bool succ = false;
if (p.PropertyType == destObj.GetType())
{
succ = true;
}
else
{
if (p.PropertyType == typeof(int))
{
succ = true;
int tmpInt = 0;
int.TryParse(destObj.ToString(), out tmpInt);
destObj = tmpInt;
}
else if (p.PropertyType == typeof(long))
{
succ = true;
long tmpLong = 0;
long.TryParse(destObj.ToString(), out tmpLong);
destObj = tmpLong;
}
else if (p.PropertyType == typeof(bool))
{
succ = true;
bool tmpBool = false;
bool.TryParse(destObj.ToString(), out tmpBool);
destObj = tmpBool;
}
else if (p.PropertyType == typeof(DateTime))
{
succ = true;
DateTime tmpDateTime;
DateTime.TryParse(destObj.ToString(), out tmpDateTime);
destObj = tmpDateTime;
}
else if (p.PropertyType == typeof(float))
{
succ = true;
float tmpFloat;
float.TryParse(destObj.ToString(), out tmpFloat);
destObj = tmpFloat;
}
else if (p.PropertyType == typeof(decimal))
{
succ = true;
decimal tmpDecimal;
decimal.TryParse(destObj.ToString(), out tmpDecimal);
destObj = tmpDecimal;
}
else if (p.PropertyType == typeof(double))
{
succ = true;
double tmpDouble;
double.TryParse(destObj.ToString(), out tmpDouble);
destObj = tmpDouble;
}
else if (p.PropertyType == typeof(char))
{
succ = true;
char tmpChar;
char.TryParse(destObj.ToString(), out tmpChar);
destObj = tmpChar;
}
else if (p.PropertyType == typeof(Int16))
{
succ = true;
Int16 tmpInt16;
Int16.TryParse(destObj.ToString(), out tmpInt16);
destObj = tmpInt16;
}
else
{
succ = false;
}
}
if(succ)
{
p.SetValue(obj, destObj, null);
}
}
}
}
}
return obj;
}