0

我试图让一个对象的构造函数将一个字段初始化为某个东西,暂停 30 秒,然后将其设置为其他东西。

这是我的代码:

namespace Practice
{
    public enum TransactionStatus { Pending, Complete }

    public class Transaction
    {
        private TransactionStatus status;

        public Transaction()
        {
            this.status = TransactionStatus.Pending;
            //(I'm trying to set this to TransactionStatus.Complete after 30 seconds. What do I do afterwards?)
        }

        // Here is the method to do it... Am I right to think that.status this must be reset this.status in the constructor?
        public TransactionStatus SetStatus()
        {
            // sleep for 30 seconds and then proceed.
            System.Threading.Thread.Sleep(3000);
            return TransactionStatus.Complete;
        }
    }
4

2 回答 2

4

老实说,我不会把它放在构造函数中。我会在主代码中这样做:

TransactionStatus status = new TransactionStatus();

Thread.Sleep(3000);

status.SetStatus();

当然这会阻塞整个程序。如果您不希望这样,则必须编写自己的函数并将其作为单独的线程调用。再次在主代码中。

那就是说我真的不明白你为什么要做这样的事情。

于 2011-11-20T08:50:10.060 回答
3

这是另一种作弊方法,因为您说您使用的是 toString();

private DateTime called;

public TranlationStatus()
{
    this.called = DateTime.Now; 
}

public ToString()
{
    if (this.called - DateTime.Now < new TimeSpan(0,0,20))
    {
        return TransationStatus.Pending.ToString();
    }
    else
    {
        return TransactionStatus.Complete.ToString();
    }
}
于 2011-11-20T08:55:51.120 回答