SPContext.cururent.web.urlとspcontext.current.siteの違いは、SPSiteオブジェクトを使用するとき

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/95812

  •  10-12-2019
  •  | 
  •  

質問

SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

SPSite spsite2=SPContext.Current.Site;
.

違いとは何ですか?いつ使用するのかを決めますか?

両方とも私たちにサイトコレクションオブジェクトを与えます。

例:SPWeb spweb=spsite1.RootWeb;spsite2.RootWeb;と同じ意味であるため、なぜそれを実行する2つの方法がありますか?

役に立ちましたか?

解決

SPSite spsite1=new SPSite(SPContext.Current.Web.Url); will give you SPSite object. But it will be site collection object only when SPContext.Current.Web.Url is that of root web. If the web object is that of a sub site then SPSite object won't be a site collection object. The second statement SPSite spsite2=new SPSite(SPContext.Current.Site); is wrong because there is no overload of SPSite which has SPSite as parameter.

UPDATE

If the intention is to get the rootweb then second is a better way of doing it as you are not instantiating a new SPSite object. Moreover, in the first case you will need to dispose SPSite object as you are creating a new one compared to second in which SPSite is retrieved through SPContext which should not be disposed explicitly.

他のヒント

The both site1 and site2 returns the same site collection (SPSite) object. By calling RootWeb property on both objects, We can get the same top-level web site (SPWeb) object.

Instruction1: SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

Process: If we are in subsite and we are calling the above code, first it get the current subsite web url and pass it to SPSite constructor to get the current Site Collection object.

Instruction2: SPSite spsite2 = SPContext.Current.Site;

Process: Now we are in subsite and we are calling the above code, which directly retrives the Site Collection object. There is no looking for web url parameter to get the SiteCollection.

Result:

spsite1.RootWeb and spsite2.RootWeb returns the same Top-Level web SPWeb object.

spsite1.OpenWeb() returns the subsite (SPWeb) object if we are in subsite. spsite2.OpenWeb() returns the top-level site (SPWeb) object, even we are in subsite.

For the spsite1, we have to call dispose method to dispose the SPSite object. But for the spsite2, the sharepoint will take care on disposing of SPSite object.

ライセンス: CC-BY-SA帰属
所属していません sharepoint.stackexchange
scroll top