获取实体类名称属性与值

此处T 为实体类具体类型根据传入实体而定

string tableName = typeof(T).Name; //获取成员名称

PropertyInfo[] allPro = typeof(T).GetProperties(); //获取所有公共属性

 foreach (PropertyInfo pro in allPro)
            {
                object[] attrs = pro.GetCustomAttributes(true);

                if (attrs.Length <= 0)
                {
                    InsertField.Append(pro.Name);
                    InsertField.Append(",");
                    object value = pro.GetValue(entity, null);
                    if (value == null)
                    {
                        InsertValue.Append(value == null ? "NULL" : value);
                        InsertValue.Append(",");
                        updateFiled.Append(pro.Name);
                        updateFiled.Append("=");
                        updateFiled.Append(value == null ? "NULL" : value);
                        updateFiled.Append(",");
                    }
                    else
                    {
                        switch (value.GetType().Name)
                        {
                            case "String":
                                value = value.ToString().Replace("'", "''");
                                InsertValue.Append("N'");
                                InsertValue.Append(value);
                                InsertValue.Append("',");
                                updateFiled.Append(pro.Name);
                                updateFiled.Append("=N'");
                                updateFiled.Append(value);
                                updateFiled.Append("',");
                                break;

            }
                    }
                }
            }

你可能感兴趣的:(属性)