0

在 onDestroy 方法中,在尝试关闭对象/将其关闭/等之前确定对象是否实际初始化的正确方法是什么?

例如,哪个更好:

protected void onDestroy()
{
    if(tts != null)
    {
        tts.shutdown();
    }

    if(dbWord != null)
    {
        dbWord.close();
    }

    super.onDestroy();
}

或这个:

protected void onDestroy()
{
    if(tts instanceof  null)
    {
        tts.shutdown();
    }

    if(dbWord instanceof TextToSpeech)
    {
        dbWord.close();
    }

    super.onDestroy();
}
4

2 回答 2

2

使用 != 而不是 instanceOf 来检查变量是否已初始化。instanceOf 执行在这种情况下您不需要的额外类型检查。

于 2011-10-05T06:28:15.487 回答
1

!=,不要用instanceOf。当你声明一个对象时,它已经是某个类的实例,即使它没有初始化,肯定是 NULL。
你的第一个是正确的处理方式。

于 2011-10-05T06:25:55.310 回答