如何检查 Panel 是否具有对象的实例

How to check if Panel has an instance of an object

在代码隐藏中我声明了一个面板:

Panel customPanel = new Panel(); // or simply Panel customPanel;

然后我可以将其分配给现有面板或不分配给它:

if (blablabla) customPanel = otherPanel;

然后我需要关注 customPanel 如果它被分配:

customPanel.focus(); // Object reference not set to an instance of an object

如何检查 customPanel 是否设置为实例?

if (customPanel != null) // the same

它仅在“blablabla”条件为真且 customPanel 分配给面板时有效。

你可以像下面这样使用 try catch 块

try
{
    customPanel.focus();
}
catch(Exception nullObjectException)
{
    //do error handling 
}