C# - Creating a 'var' array of a fixed size? - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

However, you cannot create a var array, as var is not a type, but a keyword used in place of a type, like C++11s auto. You will have to define a ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore C#-Creatinga'var'arrayofafixedsize?[closed] AskQuestion Asked 8years,4monthsago Modified 8years,3monthsago Viewed 20ktimes 0 1 Closed.ThisquestiondoesnotmeetStackOverflowguidelines.Itisnotcurrentlyacceptinganswers. Thisquestionappearstobeoff-topicbecauseitlackssufficientinformationtodiagnosetheproblem.Describeyourprobleminmoredetailorincludeaminimalexampleinthequestionitself. Closed8yearsago. Improvethisquestion I'mtryingtocreateanarrayoftypevarwithafixedlength.I'musingitinavarLinkedListclassthatIcreated.IknowthesizeofthearrayIwanttocreate,don'tknowwhat'sthecorrectsyntax? Here'sthecode: publicdynamicToArray() { intcounter=0; if(this.head==null) returnnull; else counter=1; ListEntryi=this.head; while(i.Next!=null) { counter++; i=i.Next; } vararray=new[counter]; i=this.head; for(intj=0;jthat'spartoftheframework?(andthathasToArray()viaIEnumberable) – Linky Feb24,2014at22:44  |  Show2morecomments 3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 9 I'mtryingtocreateanarrayoftypevar varisnotatype,it'sjustasyntacticsugarforimplicittypedefinition.Youneedtospecifyyourarraytype: vararray=newYourType[counter]; Withusingvaryouletthecompilertoinferthetype.Butinthiscaseitworkslikeashortcut.Anywayit'susefulwhenyouarenotsureaboutthereturningtypeofanexpressionormethod(forexampleit'susefulwhenusingLINQ). vararray=new[counter]; Inthislineifyoumeantocreateanarraythatcancontainsanytypeofelementyoucancreateanarrayofobjectsordynamic: vararray=newobject[counter]; Or: vararray=newdynamic[counter]; Share Improvethisanswer Follow editedFeb24,2014at22:22 answeredFeb24,2014at22:12 SelmanGençSelmanGenç 97.6k1313goldbadges116116silverbadges182182bronzebadges Addacomment  |  0 Youprobablywantthis: vararray=newdynamic[counter]; HoweverIamnotsurewhyyouwanttousedynamichereandreturnadynamicfromyourmethod.YouprobablyalreadyknowthetypeofListEntry.Data-youwouldprobablywanttoreturnanarrayofthattype. Share Improvethisanswer Follow answeredFeb24,2014at22:22 YK1YK1 6,43111goldbadge1919silverbadges2727bronzebadges 2 Ifhedoeswanttoreturnadynamic,sayforexample,becauseListEntry.Dataisdynamic,heprobablyreallywantstoreturnadynamic[]. – JoelRondeau Feb24,2014at22:24 @JoelRondeau:becauseListEntry.Dataisdynamic-agreed.Asfarascompilerisconcerned,ifthemethoddefinesreturningdynamichecouldreturnanythingincludingdynamic[].Butwhatyousuggestwillmakecodemorereadable. – YK1 Feb24,2014at22:31 Addacomment  |  0 Youneedtospecifythearraytype,orit'slikegoingtoasweetshopandsaying"canIhaveabagof"andnotsayingwhattypeyouwouldlike,inthiscasetothecompiler.Todeclareanarray,youcando vararray=newtype[counter]; However,youcannotcreateavararray,asvarisnotatype,butakeywordusedinplaceofatype,likeC++11sauto.Youwillhavetodefineaspecifictypeforyourarrayoryouwillhitproblems. Foryourcase,youneedadynamicorobjectarray. vararray=newdynamic[counter]; Or vararray=newobject[counter]; Share Improvethisanswer Follow editedFeb25,2014at16:16 answeredFeb24,2014at22:31 JosephJoseph 56911goldbadge55silverbadges1212bronzebadges Addacomment  |  Nottheansweryou'relookingfor?Browseotherquestionstaggedc#arraysdynamicimplicit-conversionoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Visitchat Related 3965 CreateArrayListfromarray 4645 HowdoIcheckifanarrayincludesavalueinJavaScript? 2891 Howtoappendsomethingtoanarray? 2900 DeletinganelementfromanarrayinPHP 3839 Howtoinsertanitemintoanarrayataspecificindex(JavaScript) 3695 Sortarrayofobjectsbystringpropertyvalue 3741 LoopthroughanarrayinJavaScript 10696 HowcanIremoveaspecificitemfromanarray? 5383 For-eachoveranarrayinJavaScript HotNetworkQuestions UVUnwrapontocylinder WhatcanIdoifaflightdelaymakesmemissthetransferfromtheairport? WhywouldanyonebuyaPonyoveraMule? WhatarethecorrectspecsforanSNESpowersupply? Canthepatentandpaperhavedifferentauthors(assumetheyincludethesamecontent)? howdoimakethiscookielookmorerealistic Doesmycathatemenow FindoutvalueofpFcapacitors IgnoreFileswhencopyingusingscp JPLHorizons-"highlyaccuratemeasurementsofplanetarypositions"-howdotheydoit? SeparationoftheChurchandStateinHinduism Firsttimeflyingwithcarryononly.CanIcarrydoubleedgedrazorbladeswithme? WhydoIgetaccostedfortakingphotosofawarmemorial? JustificationforaMagicschoolbeingdangerous Dosymmetricalairfoilsgenerateinduceddrag? IsDaryl'sMailLegitThisTime? Isitpracticaltopreventa51%-attackbyhavingasecondminingalgorithm? Satyricon136.7-8 Whydoprogunandantiabortion(andviceversa)viewsgotogetherintheUSA? WhatarethemainargumentsusedbyChristianpro-liferstojustifytheirstanceagainstabortion? RelationshipbetweentheTQFTsinKapustin-WittenandBen-Zvi-Sakellaridis-Venkatesh HowcanIaddalayerofmeaningtoanevilcampaign? Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? CantheEnormousTentaclesee? morehotquestions lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?