如何:使用条件范围

上次修改时间: 2011年8月22日

适用范围: SharePoint Foundation 2010

在 SharePoint Online 中提供

若要按条件执行代码,可使用 ConditionalScope 类来设置条件。如果满足条件,则该类的 StartScope() 方法会指定要完成的操作,并且该类的 TestResult 属性会包含测试条件的结果。

以下示例将为一个网站集检索并显示某个特定列表模板类型的标题,前提是该列表存在并且当前用户有权管理列表。

备注

ECMAScript(JavaScript、JScript) 对象模型未包括 .NET 托管对象模型和 Silverlight 对象模型中的 ConditionalScope 类的等效项。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            Web oWebsite = clientContext.Web;
            List oList = oWebsite.GetCatalog(ListTemplateType.WebPartCatalog);

            BasePermissions permissions = new BasePermissions();
            permissions.Set(PermissionKind.ManageLists);

            ConditionalScope scope = new ConditionalScope(
                clientContext,
                () => oList.ServerObjectIsNull.Value != true
                    && oWebsite.DoesUserHavePermissions(permissions).Value == true);

            using (scope.StartScope())
            {
                clientContext.Load(oList,
                    list=>list.Title);
            }

            clientContext.ExecuteQuery();

            Console.WriteLine(scope.TestResult.Value);

            if (scope.TestResult.Value)
            {
                Console.WriteLine(oList.Title);
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class Program

        Public Shared Sub Main()

            Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
            Dim oWebsite As Web = clientContext.Web
            Dim oList As List = oWebsite.GetCatalog(ListTemplateType.WebPartCatalog)

            Dim permissions As New BasePermissions()
            permissions.Set(PermissionKind.ManageLists)

            Dim scope As New ConditionalScope(clientContext, _
                Function() oList.ServerObjectIsNull.Value <> True _
                    AndAlso oWebsite.DoesUserHavePermissions(permissions).Value = True)

            Using scope.StartScope()
                clientContext.Load(oList, Function(list) list.Title)
            End Using

            clientContext.ExecuteQuery()

            Console.WriteLine(scope.TestResult.Value)

            If scope.TestResult.Value Then
                Console.WriteLine(oList.Title)
            End If
        End Sub
    End Class
End Namespace

请参阅

概念

如何:使用异常处理范围

常见编程任务

其他资源

客户端类库