1

I have a main form where when a user clicks a button it brings up a balloon tip. The balloon tip is an object instantiated within my Main form class from my BalloonTip class. I then have a second form for settings. When the user clicks something in the settings form a balloon tip occurs as well. I currently have a balloontip object instantiated in my Main class as well as my SettingsForm class. My two questions are:

  1. Is there a more appropriate way to deal with this type of situation?
  2. If creating an object twice 1 in each class, will it cause any kind of ambiguity in the compiler if the objects have the same name (i.e. objectBalloon)?
4

1 回答 1

3

当你实例化一个对象时,它总是在一定的范围内。

例如:

public void DoSomething()
{
    BalloonTip b = new BalloonTip();

    DoSomethingElse();
}

public void DoSomethingElse()
{
    BalloonTip b = new BalloonTip();
}

会给你两个不同的 BalloonTip 实例,它们都称为“b”,但它们都只在声明它们的函数范围内有效。

您应该将类​​定义视为可以实例化多个对象的蓝图。在一个范围内,您可以有多个实例,但它们应该具有不同的名称。

当范围不重叠时,您可以使用相同的名称来指向不同的实例。

您还可以将实例传递给另一个方法,并且在该函数中您可以通过另一个名称引用该实例。

public void DoSomething()
{
    BalloonTip b = new BalloonTip();

    DoSomethingElse(b);
}

public void DoSomethingElse(BalloonTip c)
{
  // c points to the same instance as b in the previous function
}
于 2011-12-18T18:47:47.987 回答