Example #1
0
        public static T CreateItem <T>(DataRow row)
        {
            T obj = default(T);

            if (row != null)
            {
                obj = Activator.CreateInstance <T>();
                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
                    if (prop == null)
                    {
                        continue;
                    }
                    Type type = prop.PropertyType;
                    try
                    {
                        object value = row[column.ColumnName];
                        if (value != DBNull.Value)
                        {
                            if (column.ColumnName.Contains("json"))
                            {
                                prop.SetValue(obj, MessageConvert.DeserializeObject(("" + value).Replace("$", ""), type), null);
                            }
                            else if (type.Name == "String")
                            {
                                prop.SetValue(obj, Convert.ToString(value), null);
                            }
                            else if (type.Name == "Single")
                            {
                                prop.SetValue(obj, Convert.ToSingle(value), null);
                            }
                            else if (type.Name == "Nullable`1" || type.Name == "DateTime")
                            {
                                var t         = Nullable.GetUnderlyingType(type) ?? type;
                                var safeValue = (value == null) ? null : Convert.ChangeType(value, t);
                                prop.SetValue(obj, safeValue, null);
                            }
                            else
                            {
                                prop.SetValue(obj, value, null);
                            }
                        }
                    }
                    catch
                    {
                        // You can log something here
                        throw;
                    }
                }
            }

            return(obj);
        }
Example #2
0
        public static T DeepClone <T>(this T a)
        {
            string mess = MessageConvert.SerializeObject(a);

            return(mess.DeserializeObject <T>());
        }