代码之家  ›  专栏  ›  技术社区  ›  Wildhorn

如何访问内部类中的outter类变量

  •  0
  • Wildhorn  · 技术社区  · 14 年前

    好的,我正在制作一个类的包装器,这个类有很长的路径来获取变量。举例来说,它有以下几点:

    Class1.Location.Point.X
    Class1.Location.Point.Y
    Class1.Location.Point.Z
    Class1.Location.Curve.get_EndPoint(0).X
    Class1.Location.Curve.get_EndPoint(0).Y
    Class1.Location.Curve.get_EndPoint(0).Z
    Class1.Location.Curve.get_EndPoint(1).X
    Class1.Location.Curve.get_EndPoint(1).Y
    Class1.Location.Curve.get_EndPoint(1).Z
    

    现在,在我的包装里,我想把它简化为:

    Wrapper.X
    Wrapper.Y
    Wrapper.Z
    Wrapper.P0.X
    Wrapper.P0.Y
    Wrapper.P0.Z
    Wrapper.P1.X
    Wrapper.P1.Y
    Wrapper.P1.Z
    

    public class Wrapper
    {
        protected Class1 c1 = null
        public Wrapper(Class1 cc1)
        {
             c1 = cc1;
        }
    
        public int X
        {
                get{return C1.Location.Point.X;}
        }
        public int Y
        {
                get{return C1.Location.Point.Y;}
        }
        public int Z
        {
                get{return C1.Location.Point.Z;}
        }
    }
    

    现在我的问题是P0.X和cie。我不知道怎么做。我试过使用一个子类,但它不允许我访问变量c1。我该怎么做?

    2 回复  |  直到 14 年前
        1
  •  0
  •   Wildhorn    14 年前

    好吧,我想出来了(看来我需要在这里发布一个问题来自己解决我的很多东西)。

    是相当基本的东西,我不明白为什么我没有更快地解决它。

    我创建了一个子类Point0(Class1 c1),并在包装器中添加了一个名为Point0的变量Point0和一个名为P0的属性,该属性返回Point0,所以它给了我Wrapper.P0.X

        2
  •  0
  •   drovani    14 年前

    有两种方法可以得到与你想要的相似的东西。 可以在包装器上实现索引属性

    class Wrapper{
      public int this[int index]{
        get{ return C1.Location.Curve.get_EndPoint(index); }
      }
    }
    

    Wrapper[0].X
    

    或者,如果您真的想拥有“P0”和“P1”的属性,可以让它们返回get_EndPoint(int)返回的对象(正如Frederic在他的评论中建议的那样)。

    class Wrapper{
      public EndPoint P0{
        get{ return C1.Location.Curve.get_EndPoint(0); }
      }
    }