c# - Class vs. Public Class - Stack Overflow

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

Without specifying public the class is implicitly internal . This means that the class is only visible inside the same assembly. Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Classvs.PublicClass AskQuestion Asked 10yearsago Modified 10yearsago Viewed 50ktimes 68 15 Whatisthedifferencebetween: namespaceLibrary{ classFile{ //codeinsideit } } and: namespaceLibrary{ publicclassFile{ //codeinsideit } } Sowhatwillbethedifferencebetweenpublicclassandclass? c#classpublic Share Follow editedSep12,2012at16:51 driis 158k4545goldbadges267267silverbadges337337bronzebadges askedSep12,2012at16:47 user1678541user1678541 3 15 Itslikeagovernmentbodykeepingnuclearlaunchcodessecretversuswearingatee-shirtthathasthelaunchcodesonit. – ChaosPandion Sep12,2012at16:50 7 Notethatit'sgoodpracticetoalwaysaddaccessspecifiersratherthanrelyingonlanguagedefaults.Thishelpscaseswherepeopledon'tknowwhatitis,don'tremember,mistakenlybelievethatitissomethingthat'snotcorrect,believethatyoujustforgottoaddit(andaddsomethingotherthanthedefault),etc.Ittakessolittleeffort,anditreallyhelpsreadability. – Servy Sep12,2012at16:51 @ChaosPandionIdon'tknow,I'msuresomewherethere'sat-shirtwith"000"writtenonit.(WhichwasonceactuallythecodetoonelevelofsecurityonUSmissilelaunch,thoughonlyalevelmostofthepeoplethoughtwaspointlessanyway). – JonHanna Sep12,2012at17:08 Addacomment  |  3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 74 Withoutspecifyingpublictheclassisimplicitlyinternal.Thismeansthattheclassisonlyvisibleinsidethesameassembly.Whenyouspecifypublic,theclassisvisibleoutsidetheassembly. Itisalsoallowedtospecifytheinternalmodifierexplicitly: internalclassFoo{} Share Follow answeredSep12,2012at16:48 driisdriis 158k4545goldbadges267267silverbadges337337bronzebadges 1 3 Whatdoesassemblymean@driis?Canyouexplainwhatitmeanstobeisnidethesameassemblyvsoutside? – edo101 May19,2020at4:33 Addacomment  |  24 Theformerisequivalentto: namespaceLibrary{ internalclassFile{ //codeinsideit } } Allvisibilitiesdefaulttotheleastvisiblepossible-privateformembersofclassesandstructs(methods,properties,fields,nestedclassesandnestedenums)andinternalfordirectmembersofnamespaces,becausetheycan'tbeprivate. internalmeansothercodeinthesameassemblycanseeit,butnothingelse(barringfriendassembliesandtheuseofreflection). Thismakessensefortworeasons: Youshouldbeconsciouslymakingthingsusetheleastvisibilitypossibleanyway,tostrengthenyourencapsulation. Iftheydefaultedtopublicyoucouldaccidentallymakesomethingpublicthatshouldbeprivateorinternal.Ifyouaccidentallymakesomethingnotvisibleenough,yougetanobviouscompileerrorandfixit.Ifyouaccidentallymakesomethingtoovisibleyouintroduceaflawtoyourcodethatwon'tbeflaggedasanerror,andwhichwillbeabreakingchangetofixlater. It'softenconsideredbetterstyletobeexplicitwithyouraccessmodifiers,tobeclearerinthecode,justwhatisgoingon. Share Follow answeredSep12,2012at16:55 JonHannaJonHanna 108k99goldbadges143143silverbadges245245bronzebadges Addacomment  |  1 Bydefault,allclasses(andalltypesforthatmatter)areinternal,soinorderforthemtobeaccessiblefromtheoutside(sansstufflikeInternalsVisibleToAttribute)youhavetomakethempublicexplicitly. Share Follow answeredSep12,2012at16:48 AntonGogolevAntonGogolev 111k3838goldbadges194194silverbadges282282bronzebadges 2 2 Nope,they'reinternal.Everythinginsidetheclassesareprivatebydefaultthough. – LouisKottmann Sep12,2012at16:49 3 -1,becausetheansweriswrong.Thenremoved-1afteryoueditedtheanswer:-) – driis Sep12,2012at16:50 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy TheOverflowBlog IspenttwoyearstryingtodowhatBackstagedoesforfree Aserialentrepreneurfinallyembracesopensource(Ep.486) FeaturedonMeta PlannedmaintenancescheduledforWednesday,21September,00:30-03:00UTC... RecentColorContrastChangesandAccessibilityUpdates Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... ShouldIexplainotherpeople'scode-onlyanswers? Linked 11 HttpClientExceptionwhenconnectingtoworkinghubfromSignalR.NETClient 2 Publicclass,butprivatemembervariables? Related 7299 WhatisthedifferencebetweenStringandstringinC#? 858 What'sthedifferencebetweenstructandclassin.NET? 1614 WhatisthedifferencebetweenconstandreadonlyinC#? 2328 Should'using'directivesbeinsideoroutsidethenamespace? 2181 WhenshouldIuse'self'over'$this'? 3535 Whatisthedifferencebetweenpublic,protected,package-privateandprivateinJava? 3290 Caseinsensitive'Contains(string)' 1110 Whatisthedifferencebetweenpublic,private,andprotected? 1758 Whatdoes"Couldnotfindorloadmainclass"mean? 1768 AddTransient,AddScopedandAddSingletonServicesDifferences HotNetworkQuestions CobordismcohomologyofLiegroups Immutablematrixclasswithmathematicalmethods HowtogetthedimensionofAtkin-Lehnereigenspaceordoyouhaveanydataalreadyobtained? DependentVariabletakesonthevalues0,1,2,3-Whatistheright(logistic)regressionmodeltouse? Canyouuseyourbonusactiontomove,butnotattackwith,aspiritualweapon? SciencefictionshortstoryinwhichEinsteinisclonedbutshowsnointerestinmuchexceptplayinghisviolin InterpretneuralnetworklikethelinearregressionequationsuchashowmuchwillYchangeifwechangeX1andkeeptheothervariablesfixed Centerofawirenutholdingneutralwiresisburned,butitdoesn'tseemloose Weredoctorswhoweredraftedinthe1950/1960years,compelledtotakeanofficer'soathofallegiance? ForwhatVulpes-->Vulpecula,butSorexneverwillbeSoreculus IstheRds(on)ofaMOSFETtypicallyspecifiedattheboundaryofthesaturationandtrioderegions? Whatisatuneorsongcalledthatisrecurrentlyusedsopeoplestarttoassociatethetuneorsongwiththatwhatitisusedwith? Cananon-UScitizenboardanoutboundplane(leavetheUS)withoutapassportbacktohomecountry? Nitrogentrifluorideasahighdensityoxidiser lscommandline-wrapprevention Tacx/Wahoo/Zwiftturbotraineradvice/recommendations? Forneuralnetworks,ismini-batchingdonepurelybecauseofmemoryconstraints? CalculatingPiusingtheGregoryLeibnizseriesuntilnterms Doconduitnippleshavetobestraight? TipsonwheretobuyclothesforcoldweatherinLille,France? Howtopronounce"Gröbner"? SelectiveCaesarCipher HasNASAreleasedanyJWSTimagesofTrappist-1?Ifnot,why? WouldtheDzhanibekoveffectbeaproblemforVonBraunWheels? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?