我认为你的问题在某种程度上已经包含了正确的答案。
为了确定客户端对象属性是否已加载,可以使用以下方法:
测试
测试用例1:仅加载标量属性
ctx.Load(ctx.Web, w => w.Title);
ctx.ExecuteQuery();
//Results:
ctx.Web.IsObjectPropertyInstantiated("Lists") False
ctx.Web.IsPropertyAvailable("Title") True
测试用例2:仅加载复合属性
ctx.Load(ctx.Web, w => w.Lists);
ctx.ExecuteQuery();
//Results:
ctx.Web.IsObjectPropertyInstantiated("Lists") True
ctx.Web.IsPropertyAvailable("Title") False
测试用例3:同时加载标量和组合属性
ctx.Load(ctx.Web, w=>w.Lists,w=>w.Title);
ctx.ExecuteQuery();
//Results
ctx.Web.IsObjectPropertyInstantiated("Lists") True
ctx.Web.IsPropertyAvailable("Title") True
如何动态确定客户端对象属性是否已加载?
由于ClientObject.IsPropertyAvailable和ClientObject.IsObjectPropertyInstantiated方法需要将属性名称指定为字符串值,这可能会导致拼写错误。因此,我通常更喜欢使用以下扩展方法:
public static class ClientObjectExtensions
{
public static bool IsPropertyAvailableOrInstantiated<T>(this T clientObject, Expression<Func<T, object>> property)
where T : ClientObject
{
var expression = (MemberExpression)property.Body;
var propName = expression.Member.Name;
var isCollection = typeof(ClientObjectCollection).IsAssignableFrom(property.Body.Type);
return isCollection ? clientObject.IsObjectPropertyInstantiated(propName) : clientObject.IsPropertyAvailable(propName);
}
}
使用方法
using (var ctx = new ClientContext(webUri))
{
ctx.Load(ctx.Web, w => w.Lists, w => w.Title);
ctx.ExecuteQuery();
if (ctx.Web.IsPropertyAvailableOrInstantiated(w => w.Title))
{
}
if (ctx.Web.IsPropertyAvailableOrInstantiated(w => w.Lists))
{
}
}
EnsureProperty
和EnsureProperties
方法。 - rlv-dan