简体   繁体   English

如何从基类数组访问派生类字段?

[英]How to access a derived class field from a base class array?

I looked through similar threads and they all pertain to C++, so I assume it's better to ask than to just fumble around. 我浏览了相似的线程,它们都与C ++有关,所以我认为最好问一下,而不是随便逛逛。 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: 假设foo是一个没有变量/方法的自定义类:

public class foo
{

}

and that bar is a custom class derived from foo : bar是从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 foo s. 在我的fooArray ,我需要从fooArray[2] (它是一个bar访问变量fooBar ,但是由于该变量未出现在基类中,因此它不会显示在foo s数组中。 Is there any way I can access it? 有什么办法可以访问它?

Edit: In the application code, both foo and bar have the required constructors and other settings. 编辑:在应用程序代码中,foo和bar都具有必需的构造函数和其他设置。

You could cast. 你可以投。 In order to be safe you should use the as keyword: 为了安全起见,您应该使用as关键字:

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 : 因为foo类没有fooBar字段,所以除非将变量强制转换为Bar否则就无法访问它:

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

Note: fooBar field should be public .Fields are private by default. 注意: fooBar字段应为public 。默认情况下,字段为private

You can cast one of the items in the array to bar and as access it that way, 您可以将数组中的一项强制转换为bar并以此方式进行访问,

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

Or use the as operator to treat the object as type bar , 或使用as运算符将对象视为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 . 但是,在示例fooBar定义它的方式是private You would have to make it public to access it outside of the class. 您必须将其public以便在课堂之外访问它。

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

In order to access it you would need to cast the value to a bar instance 为了访问它,您需要将值强制转换为bar实例

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

Note that if fooArray[2] isn't actually an instance of bar this code will throw an exception. 请注意,如果fooArray[2]实际上不是bar的实例,则此代码将引发异常。 If you want to do this only if fooArray[2] is a bar then do the following 如果仅在fooArray[2]bar的情况下要执行此操作,请执行以下操作

bar b = fooArray[2] as bar;
if (b != null) {
  int i = b.foobar;
  ...
}

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

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