简体   繁体   English

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

[英]How to have access to outter class variable inside an inner class

Ok, I am making a wrapper of a class that has very long path to get variables. 好的,我正在包装一个类,该类具有很长的获取变量的路径。 By example, it has the following: 例如,它具有以下内容:

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

Now, in my wrapper, I would like to simplify it to this: 现在,在我的包装器中,我想将其简化为:

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

My wrapper look like about this: 我的包装器看起来像这样:

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;}
    }
}

Now my problem is the P0.X and cie. 现在我的问题是P0.X和cie。 I don't know how to do it. 我不知道该怎么做。 I tried with a subclass, but it doesnt allow me to get access to my variable c1. 我尝试了一个子类,但是它不允许我访问变量c1。 How can I do this? 我怎样才能做到这一点?

Well, I figured it out (it seems I need post a question here to figure out much of my stuff by myself). 好吧,我知道了(似乎我需要在这里发布一个问题,以便自己找出我的大部分东西)。

Was rather basic stuff, I dont understand why I didnt figure it out faster. 是相当基本的东西,我不明白为什么我没有更快地弄清楚。

I made a subclass Point0(Class1 c1) and added to my Wrapper a variable Point0 named point0 and a property named P0 that return point0, so it gives me Wrapper.P0.X 我创建了一个子类Point0(Class1 c1),并将一个名为point0的变量Point0和一个返回point0的名为P0的属性添加到了Wrapper,所以它给了我Wrapper.P0.X

Two ideas to get something similar to what you are looking for. 得到与您正在寻找的东西相似的两个想法。 You could implement an indexed property on Wrapper 您可以在Wrapper上实现索引属性

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

This would leave the user calling this with something similar to: 这将使用户使用类似于以下内容的方式来调用它:

Wrapper[0].X

Alternatively, if you really want to have the properties of "P0" and "P1", you can just make them return the object returned by get_EndPoint(int) (as Frederic suggested in his comment). 另外,如果您确实希望具有“ P0”和“ P1”的属性,则可以使它们返回由get_EndPoint(int)返回的对象(如Frederic在其评论中建议的那样)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM