2010-02-04 45 views
0

我收到了类似的评论设定条件时的逻辑问题

此检查(if (rp != null))不应该在这里。当rp为null时,变量irp.ResourcePolicy应设置为null,因为资源策略是未知的。否则,将使用先前的值并且以前的值可能不正确。

// Search for the specified resource policy 
           ResourcePolicy rp = null; 
           try 
           { 
            int rpindex = allObjects.Find(new Guid(policyGuid)); 
            if (rpindex != -1) 
            { 
             rp = (ResourcePolicy)allObjects.GetAt(rpindex); 
            } 
           } 
           catch (System.Exception err) 
           { 
            SpoDebug.DebugTraceSevere(func, "Bad GUID: " + policyGuid + " Exception: " + err.Message); 
            rp = null; 
           } 

           if (rp == null) 
           { 
            SpoDebug.DebugTraceSevere(func, "Unable to find ResourcePolicy with GUID: " + policyGuid); 
           } 

           // Search for the specified host 


foreach (DataModelObject dmo in allObjects) 
{ 
    if (dmo is IResourcePolicy && string.Compare(dmo.Name, hostName, true) == 0) 
    { 
     IResourcePolicy irp = (IResourcePolicy)dmo; 
     irp.AgentVersion = agentVersion; 
     if (rp != null) // this is the condition we need to look 
     { 
      irp.ResourcePolicy = rp; 
      irp.AgentPolicyVersion.Version = Convert.ToInt64(policyVersion); 
      irp.ResourcePolicyEnabled = Convert.ToBoolean(enabled); 
     } 
     // Distribute the object without saving it. 
     SpoServer.Spurt.ServerSendObject(dmo, true, 0); 

     break; 
    } 

} 

所以我做了这种方式:

foreach (DataModelObject dmo in allObjects) 
{ 
    if (dmo is IResourcePolicy && string.Compare(dmo.Name, hostName, true) == 0) 
    { 
     IResourcePolicy irp = (IResourcePolicy)dmo; 
     irp.AgentVersion = agentVersion; 
     if (rp == null) 
     { 
      irp.ResourcePolicy = null; 
     } 
     else 
     { 
      irp.ResourcePolicy = rp; 
      irp.AgentPolicyVersion.Version = Convert.ToInt64(policyVersion); 
      irp.ResourcePolicyEnabled = Convert.ToBoolean(enabled); 
     } 

     // Distribute the object without saving it. 
     SpoServer.Spurt.ServerSendObject(dmo, true, 0); 

     break; 
    } 
} 

是足够的?

回答

1

虽然irp.ResourcePolicy = rp;在所有情况下都是正确的,所以您可能可以将其移出条件块(尽管将它放在一个块中让您对普通读者更加明显) 。

+0

u能清除这个 – peter 2010-02-04 10:17:59

1

你想要什么irp.AgentPolicyVersion.Versionirp.ResourcePolicyEnabledrp为空?我希望他们被设置为一些适当的默认值,而不是保持原样。

否则,我会写这样的:

IResourcePolicy irp = (IResourcePolicy)dmo; 
irp.AgentVersion = agentVersion; 
irp.ResourcePolicy = rp; 
if (rp != null) 
{ 
    irp.AgentPolicyVersion.Version = Convert.ToInt64(policyVersion); 
    irp.ResourcePolicyEnabled = Convert.ToBoolean(enabled); 
} 
+0

我改变了这个问题有点,,意味着添加 – peter 2010-02-04 10:24:04

+0

你默认值的意思,,是将其设置为空 – peter 2010-02-04 10:31:50

+0

@peter:那么,你的问题表明irp.ResourcePolicy可能已经有一个值了...所以我会假定irp.ResourcePolicyEnabled和irp.AgentPolicyVersion.Version也可能。我希望你想重置这些如false和0,如果rp为空。 – 2010-02-04 11:02:46