我在这个命名空间中有一个枚举:
Andish.CSS.CommonSilverLight.Enum.Billing.AccountTransacts.AccountTransactAccountType
...并使用此方法将数据集转换为类:
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
var temp = new List<T>();
try
{
var columnsNames = (from DataColumn dataColumn in datatable.Columns select dataColumn.ColumnName).ToList();
temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsNames));
return temp;
}
catch
{
return temp;
}
}
private T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value,
Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value,
Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
但是,当我调试代码并在数据集中有一个转换为枚举属性的 int 列时,这一行:
objProperty.SetValue(obj, Convert.ChangeType(value,
Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
...返回一个错误:
Value cannot be null.
Parameter name: conversionType
....发现:
Nullable.GetUnderlyingType(objProperty.PropertyType).ToString()
==
"Andish.CSS.CommonSilverLight.Enum.Billing.AccountTransacts.AccountTransactAccountType"
Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())
==
null
为什么Type.GetType
没有得到我的枚举类型?