Выкладываю часть кода моей программы, хочу чтобы вы мне указали где что лучше здесь оптимизировать исправить - C#
Формулировка задачи:
Здравствуйте, я недавно в программировании на C# поэтому тонкостей не знаю, выкладываю часть кода моей программы, хочу чтобы вы мне указали где что лучше здесь оптимизировать исправить.
/*
* Created by SharpDevelop.
* User: User
* Date: 14.12.2011
* Time: 13:15
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace osaka24
{
/// <summary>
/// Description of Courier.
/// </summary>
public class Courier: DataTable
{
private MySqlDataAdapter myAdapter;
private MySqlConnection myConnection;
public Courier(Config _Config)
{
string Connect = string.Format("Database={0}; Data Source={1}; User Id={2}; Password={3}; character set=utf8", _Config.Database, _Config.DataSource, _Config.UserId, _Config.Password);
myConnection = new MySqlConnection(Connect);
this.Columns.Add("id", System.Type.GetType("System.String"));
this.Columns.Add("name", System.Type.GetType("System.String"));
string CommandText = "SELECT id, name FROM courier";
myAdapter = new MySqlDataAdapter(CommandText, myConnection);
FillData();
}
public void FillData()
{
try
{
myConnection.Open();
myAdapter.Fill(this);
myConnection.Close();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
public void AddItem(string name)
{
MySqlCommand MyCommand = new MySqlCommand(string.Format("INSERT INTO courier (name) VALUES ('{0}')", name), myConnection);
try
{
myConnection.Open();
MyCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
this.Clear();
FillData();
}
public void DeleteItem(string id)
{
MySqlCommand MyCommand = new MySqlCommand(string.Format("DELETE FROM courier WHERE id={0}", id), myConnection);
try
{
myConnection.Open();
MyCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
this.Clear();
FillData();
}
public void DeleteAll()
{
MySqlCommand MyCommand = new MySqlCommand("TRUNCATE TABLE courier", myConnection);
try
{
myConnection.Open();
MyCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
this.Clear();
FillData();
}
}
}Решение задачи: «Выкладываю часть кода моей программы, хочу чтобы вы мне указали где что лучше здесь оптимизировать исправить»
textual
Листинг программы
namespace osaka24
{
/// <summary>
/// Description of buylist.
/// </summary>
public class BuyList: DataTable
{
private MySqlConnection myConnection;
public BuyList(MySqlConnection _myConnection)
{
myConnection = _myConnection;
this.Columns.Add("category_name", typeof(string));
this.Columns.Add("product_id", typeof(string));
this.Columns.Add("product_name", typeof(string));
this.Columns.Add("product_price", typeof(string));
this.Columns.Add("discount", typeof(string));
this.Columns.Add("count", typeof(string));
this.Columns.Add("discount_price", typeof(string));
}
//добавление товара в список покупок. Если товар присутствует в списке и скидка имеет ту же величину, то увеличивается количество
public void AddItem(int id, string discount)
{
DataRow[] FoundRows = Select(string.Format("product_id = '{0}' AND discount = '{1}'", id, discount));
if (FoundRows.Length > 0)
{
FoundRows[0]["count"] = Convert.ToInt32(FoundRows[0]["count"]) + 1;
}
else
{
try
{
myConnection.Open();
string CommandText = "SELECT category.name AS category_name, product.id AS product_id, product.name AS product_name, product.price AS product_price FROM product INNER JOIN category ON category.id = product.pid WHERE product.id = @id";
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myCommand.Parameters.AddWithValue("@id", id);
MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();
try
{
MyDataReader.Read();
decimal discountPrice = CalcDiscountPrice(discount, MyDataReader["product_price"]);
this.Rows.Add(MyDataReader["category_name"], MyDataReader["product_id"], MyDataReader["product_name"], MyDataReader["product_price"], discount, 1, discountPrice);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
MyDataReader.Close();
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
myConnection.Close();
}
}
}
//подсчет суммы
public decimal CalcSum()
{
decimal sum = 0;
foreach(DataRow Row in this.Rows)
{
sum += Convert.ToDecimal(Row["discount_price"]) * Convert.ToDecimal(Row["count"]);
}
return Math.Round(sum, 2);
}
//подсчет цены со скидкой
private decimal CalcDiscountPrice(string _discount, object _price)
{
int discount = Convert.ToInt32(_discount);
decimal price = Convert.ToDecimal(_price);
decimal discount_price = price*(1 - discount * 0.01m);
return Math.Round(discount_price, 2);
}
public void Buy()
{
//тут будет запрос на добавление в бд с датой и списком товаров.
}
}
}