質問

I looked through similar threads and they all pertain to C++, so I assume it's better to ask than to just fumble around. I have, for example, this code:

foo[] fooArray = new foo[5];
fooArray[2] = new bar();

Say that foo is a custom class with no variables/methods:

public class foo
{

}

and that bar is a custom class derived from foo:

public class bar : foo
{
    int fooBar = 0;
}

In my fooArray, I need to access the variable fooBar from fooArray[2], which is a bar, but as the variable doesn't appear in the base class, it doesn't show up in an array of foos. Is there any way I can access it?

Edit: In the application code, both foo and bar have the required constructors and other settings.

役に立ちましたか?

解決 2

You can cast one of the items in the array to bar and as access it that way,

bar barVar = (bar)fooArray[2];
int fooBarInt = barVar.fooBar;

Or use the as operator to treat the object as type bar,

bar barVar = fooArray[2] as bar;
if (barVar != null)
{
    // user barVar.fooBar;
}

However, the way it is define in your example fooBar is private. You would have to make it public to access it outside of the class.

public class bar : foo
{
    public int fooBar = 0;
}

他のヒント

You could cast. In order to be safe you should use the as keyword:

bar b = fooArray[2] as bar
if ( b != null ){
   //Do stuff with b.foobar
} else {
   //Handle the case where it wasn't actually a bar
}

Because foo class don't have fooBar field.You can't access it unless you cast your variable to Bar:

fooArray[2] = new bar();
var value = ((bar)fooArray[2]).fooBar;

Note: fooBar field should be public.Fields are private by default.

In order to access it you would need to cast the value to a bar instance

int i = ((bar)fooArray[2]).foobar;

Note that if fooArray[2] isn't actually an instance of bar this code will throw an exception. If you want to do this only if fooArray[2] is a bar then do the following

bar b = fooArray[2] as bar;
if (b != null) {
  int i = b.foobar;
  ...
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top