银行转账程序
写了一个转账的程序,本希望能利用MTS的事务来处理一些事情,结果不对。
大家帮我看看错在哪里。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.EnterpriseServices;
using Meyer.Utility;
namespace Meyer.Component
{
[Transaction(TransactionOption.Required)]
public class Account:ServicedComponent
{
private int _id;
private decimal _amount;
public Account()
{
}
public void Set(int id, decimal amount)
{
_id = id;
_amount = amount;
}
private void UpdateAmount(decimal amount)
{
const string update = "UPDATE Account SET Amount = @Amount WHERE ID = @ID";
SqlParameter[] parm = new SqlParameter[]{
new SqlParameter("@Amount", SqlDbType.Decimal),
new SqlParameter("@ID", SqlDbType.Int)
};
parm[0].Value = amount;
parm[1].Value = _id;
Database.ExecuteNonQuery(CommandType.Text, update, parm);
}
[AutoComplete(true)]
public void Deposit(decimal amount)
{
try
{
UpdateAmount(_amount + amount);
}
catch
{
throw;
}
}
[AutoComplete(true)]
public void Withdraw(decimal amount)
{
try
{
UpdateAmount(_amount - amount);
if (amount > _amount)
{
throw new Exception("余额不足");
}
}
catch
{
throw;
}
}
[AutoComplete(true)]
public void TransferFunds(Account destination, decimal amount)
{
try
{
destination.Deposit(amount);
Withdraw(amount);
}
catch
{
throw;
}
}
}
}
MainClass.cs
using System;
using Meyer.Component;
namespace Transfer
{
/// <summary>
/// MainClass 的摘要说明。
/// </summary>
public class MainClass
{
static void Main()
{
try
{
Account from = new Account();
from.Set(1, 150);
Account to = new Account();
to.Set(2, 200);
from.TransferFunds(to, 200);
}
catch(Exception exp)
{
Console.Write(exp.Message);
}
}
}
}
浙公网安备 33010602011771号