public TOutPut CopyValue<TInput, TOutPut>(TInput fromSource) where TOutPut : new()
{
/*
* 说明:TInput是数据源的类型,TOutPut是返回值类型。此方法先根据TOutPut泛型实例化一个T2类型的对象outPutValue,
* 循环outPutValue属性并且从TInput的同名属性中对应赋值
*/
TOutPut outPutValue = Activator.CreateInstance<TOutPut>();
PropertyInfo[] properties = outPutValue.GetType().GetProperties();
foreach (var property in properties)
{
var columnName = property.Name.ToLower();
object obj = null;
var fromSourceTypes = fromSource.GetType();
foreach (var fromSourceType in fromSourceTypes.GetRuntimeProperties())
{
if (fromSourceType.Name.ToLower() == columnName)
{
var columnValue = fromSource.GetType().GetProperty(fromSourceType.Name).GetValue(fromSource, null);
if (property.PropertyType.IsGenericType)
{
if (property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
obj = columnValue == null ? null : Convert.ChangeType(columnValue, Nullable.GetUnderlyingType(property.PropertyType));
}
}
else
{
var propertyTypeFullName = property.PropertyType.FullName;
if (propertyTypeFullName == "System.Guid")
{
Guid guidOutvalue = Guid.Empty;
if (columnValue != null)
{
Guid.TryParse(columnValue.ToString(), out guidOutvalue);
}
obj = guidOutvalue;
}
else if (propertyTypeFullName == "System.String")
{
obj = columnValue == null ? string.Empty : columnValue.ToString();
}
else if (propertyTypeFullName == "System.Int16")
{
Int16 intOutvalue = 0;
if (columnValue != null)
{
Int16.TryParse(columnValue.ToString(), out intOutvalue);
}
obj = intOutvalue;
}
else if (propertyTypeFullName == "System.Int32")
{
Int32 intOutvalue = 0;
if (columnValue != null)
{
Int32.TryParse(columnValue.ToString(), out intOutvalue);
}
obj = intOutvalue;
}
else if (propertyTypeFullName == "System.Int64")
{
Int64 intOutvalue = 0;
if (columnValue != null)
{
Int64.TryParse(columnValue.ToString(), out intOutvalue);
}
obj = intOutvalue;
}
else if(propertyTypeFullName== "System.Byte")
{
byte byteOutvalue = 0;
if (columnValue != null)
{
byte.TryParse(columnValue.ToString(), out byteOutvalue);
}
obj = byteOutvalue;
}
else if (propertyTypeFullName == "System.Byte[]")
{
byte[] byteArrayOutvalue = null;
if (columnValue != null)
{
byteArrayOutvalue = (byte[])columnValue;
}
obj = byteArrayOutvalue;
}
}
property.SetValue(outPutValue, obj);
break;
}
}
}
return outPutValue;
}
public List<TOutPut> CopyValue<TInput, TOutPut>(IEnumerable<TInput> fromSourceArr) where TOutPut : new()
{
List<TOutPut> outPutValues = new List<TOutPut>();
foreach (var item in fromSourceArr)
{
TOutPut t = CopyValue<TInput, TOutPut>(item);
outPutValues.Add(t);
}
return outPutValues;
}