ChrisW <ch*******@gmai l.comwrote:
So I have a class that creates threads within it. These threads are a
class underneath the parent class. I want to access values in the
parent class from the threads while they run. Yet this gives me an
error: cannot access a non-static member of outer type 'Parent.Class'
via nested type 'Parent.Class.T hread'.
So how do I access values in the parent class?
I suggest we leave threading out of it, as threads aren't classes.
Now, if you want to tell a nested type about an instance of its outer
type, you need to provide it with that information, just as if it were
any other type. Unless inner classes in Java, there's no implicit outer
class instance involved. Here's an example:
using System;
class Outer
{
private int x;
class Nested
{
Outer outer;
internal Nested(Outer outer)
{
this.outer = outer;
}
internal void Foo()
{
Console.WriteLi ne("outer.x = {0}", outer.x);
}
}
static void Main()
{
Outer o = new Outer();
o.x = 10;
Nested nested = new Nested(o);
nested.Foo();
}
}
This also demonstrates that a nested type has access to their outer
type's private members.
--
Jon Skeet - <sk***@pobox.co m>
Web site:
http://www.pobox.com/~skeet
Blog:
http://www.msmvps.com/jon.skeet
C# in Depth:
http://csharpindepth.com