Pregunta

Just a basic programming question.

public class ClassA
{
    int i = 10;
    void Start()
    {
        ClassB b = new ClassB(this);
        b.DoSomething();
    }
}

public class ClassB
{
    ClassA a;
    public ClassB(ClassA a)
    {
        this.a = a;
    }

    void DoSomething()
    {
        Console.WriteLine(a.i);
    }
}

I would really like to omit the a:

Console.WriteLine(a.i);
->
Console.WriteLine(i);

What is the most reasonable method of achieving this?

(Note: ClassB must not inherit from ClassA, as ClassA inherits from something ClassB cannot. And I suppose I should say I don't want to pass parameters to the functions, so DoSomething(i) is not applicable.)

¿Fue útil?

Solución

You can create a property. Please note that a.i still needs to be public for both your example and mine.

public class ClassB
{
    private ClassA a;

    public ClassB(ClassA a)
    {
        this.a = a;
    }

    public int i { get { return a.i; } }

    void DoSomething()
    {
        Console.WriteLine(i);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top