generics - C# can not using **as** to cast base class to derived class -


class building { }  class home: building { }  private list<building>   buildings; public t[] findbuildings<t>() {            return buildings.findall(x => x t).toarray() t[]; } 

i have list save buildings on map, , write function find building type. want using findbuildings<home>() array contains home buildings on map, when run code, found function return null, seems as did not work. mean as can not using generic type parameter?

so, change code:

private list<building>   buildings; public building[] findbuildings<t>() {            return buildings.findall(x => x t).toarray(); } 

using findbuildings<home>() home[] access home buildings on map. but...it still null.

i saw unity3d's example, show me using 'as' convert array type, why failed?

using unityengine; using system.collections;  public class example : monobehaviour {     void onmousedown() {         hingejoint[] hinges = findobjectsoftype(typeof(hingejoint)) hingejoint[];         foreach (hingejoint hinge in hinges) {             hinge.usespring = false;         }     } } 

you need this:

return buildings.oftype<t>.toarray(); 

explanation of why attempt did not work follows.

the type of expression buildings.findall(x => x t) list<building>. because buildings list<building>, , findall not magically change type of item in return value. therefore, toarray() produces building[].

the as operator returns non-null value in cases straight cast valid. since cast building[] home[] not valid, as produces null. don't confused fact casting home[] building[] valid.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -