使用'(Class)Object'类型的Initialization创建和初始化对象

时间:2013-12-28 14:02:42

标签: c#

StateObjClass State = (StateObjClass)StateObj;

有人可以解释'State'的初始化方法。需要帮助理解上述陈述。

周边代码:

private class StateObjClass
{
    // Used to hold parameters for calls to TimerTask. 
    public int SomeValue;
    public System.Threading.Timer TimerReference;
    public bool TimerCanceled;
}

public void RunTimer()
{
    StateObjClass StateObj = new StateObjClass();
    StateObj.TimerCanceled = false;
    StateObj.SomeValue = 1;
    System.Threading.TimerCallback TimerDelegate =
    new System.Threading.TimerCallback(TimerTask);

    // Create a timer that calls a procedure every 2 seconds. 
    // Note: There is no Start method; the timer starts running as soon as  
    // the instance is created.
    System.Threading.Timer TimerItem =
    new System.Threading.Timer(TimerDelegate, StateObj, 2000, 2000);

    // Save a reference for Dispose.
    StateObj.TimerReference = TimerItem;  

    // Run for ten loops. 
    while (StateObj.SomeValue < 10) 
    {
        // Wait one second.
        System.Threading.Thread.Sleep(1000);  
    }

    // Request Dispose of the timer object.
    StateObj.TimerCanceled = true;  
}

private void TimerTask(object StateObj)
{
    StateObjClass State = (StateObjClass)StateObj;
    // Use the interlocked class to increment the counter variable.
    System.Threading.Interlocked.Increment(ref State.SomeValue);
    System.Diagnostics.Debug.WriteLine("Launched new thread  " +    DateTime.Now.ToString());
    if (State.TimerCanceled)    
    // Dispose Requested.
    {
        State.TimerReference.Dispose();
        System.Diagnostics.Debug.WriteLine("Done  " + DateTime.Now.ToString());
    }
}

2 个答案:

答案 0 :(得分:1)

如果您显示周围的代码会有所帮助,但我认为StateObj可能被声明为与StateObjClass不同的类型,例如foo

object foo = new Foo();
Foo foo2 = (Foo)foo;

这是Foo,但foo被声明为object,因此无论何时在代码中使用foo,编译器都会将其视为object

为了将其分配给更加衍生的变量,例如foo2,您必须cast fooFoo

如果不这样,编译器会抱怨:

object foo = new Foo();
Foo foo2 = foo;
  

无法将类型'object'隐式转换为'Foo'

答案 1 :(得分:0)

它没有真正初始化。这种意义上的()符号实际上是一种类型转换。因此StateObj必须从StateObjClass继承,并且只是将其转换为此处并分配给State变量。

很难确切知道为什么要在这里完成,因为只有一行代码没有上下文。

如果StateObj有多个重载,通常会指定要公开的方法集。