问题描述
我不知道跳跳是否是我想要达到的目标的最佳词(因为我从未正式学习过编程),基本上我有一个带有两个内部类的类,这就是代码
using System.Drawing;
namespace Leveltar_Fresh
{
class Scene
{
private Image image;
public class Sphere : Scene
{
public Sphere()
{
}
public Sphere addClickable(int x,int y,int r)
{
Clickable clickable = new Clickable.Sphere(x,y,r);
return this;
}
}
public class Rectangle : Scene
{
public Rectangle()
{
}
public Rectangle addClickable(int x,int width,int height)
{
Clickable clickable = new Clickable.Rectangle(x,width,height);
return this;
}
}
public static Scene createNewScene(Scene scene)
{
return scene;
}
}
}
我尝试在外部类中添加一个方法,该方法可以用作该方法的另一条链
public static Scene getScene()
{
return this;
}
但是当我在链中调用此方法时,我无法访问new Scene.Sphere().addClickable(20,20,50).getScene()
的内部类,然后我都无法调用这两个内部类,因此我对Java有更多的经验,并且我知道在c#和java中使用内部类之间存在一些差异,但是是什么原因引起的,又该如何解决呢?
解决方法
在这里很难说出您要做什么。也许像这样吗?
public interface IScene
{
bool PointIsWithinScene( int x,int y);
}
public Sphere: IScene
{
public Sphere( int x,int y,int r) { ... }
public bool PointIsWithinScene( int x,int y) { return ...; }
}
public Rectangle: IScene
{
public Rectangle( int x,int w,int h) { ... }
public bool PointIsWithinScene( int x,int y) { return ...; }
}
public CompositeScene: List<IScene>,IScene
{
public CompositeScene(): base() { ... }
public bool PointIsWithinScene( int x,int y)
{
return this.Any( subScene => subScene.PointIsWithinScene( x,y));
}
}
,
我不确定我了解您要做什么。但是,调用getScene()
方法后不能访问嵌套类的原因是因为嵌套类的范围仅限于父类之内。
在回应我的评论是否需要嵌套类时,您提到您只需要用它进行代码组织,而不限制范围,因此,我建议将这些类移出。实际上,这将导致代码更简洁。
下面,我试图保留您的功能,只是使您的代码更流利。
public class Scene
{
public Scene()
{
ChildSphere = new Sphere();
ChildRectangle = new Rectangle();
}
// 2 previously nested classes are now public properties.
public Sphere ChildSphere { get; }
public Rectangle ChildRectangle { get; }
public static Scene CreateNewScene(Scene scene)
{
//logic...
return scene;
}
public Scene GetScene()
{
return this;
}
}
public class Sphere : Scene
{
public Sphere AddClickable(int x,int r)
{
Clickable clickable = new Clickable.Sphere(x,y,r);
// logic..
return this;
}
}
public class Rectangle : Scene
{
public Rectangle AddClickable(int x,int width,int height)
{
Clickable clickable = new Clickable.Rectangle(x,width,height);
// logic..
return this;
}
}
这将导致以下结果:
new Scene().ChildSphere
.AddClickable(20,20,50)
.GetScene()
.ChildRectangle
.AddClickable(20,40,60,80)
.GetScene();
我之所以包含GetScene()
方法是因为您在示例中使用了该方法。鉴于您提供的代码,我认为它用处不大。
上面的示例中需要指出的是,一旦调用此new Scene().ChildSphere
,您将无法再(通过链接)访问原始(非常第一)场景。换句话说,每个附加链都将在该点返回当前实例。
因此,根据每个链之后返回的对象,我们有:
new Scene().ChildSphere // scene1 -> scene1.ChildSphere
.AddClickable(20,50) // scene1.ChildSphere
.GetScene() // scene1.ChildSphere
.ChildRectangle // scene1.ChildSphere.ChildRectangle
.AddClickable(20,80) // scene1.ChildSphere.ChildRectangle
.GetScene(); // scene1.ChildSphere.ChildRectangle
如果您希望在任何时候回到 scene1 或其他先前的父级,则需要实现一种将父级和子级链接的方式。可能,但已将其排除在此问题之外。