设置条件时的逻辑问题

我有一个要求这个’if’结构必须改变。 由于它是当前编码的,因此仅在RM发送的策略GUID与服务器上的策略的GUID匹配时才设置代理版本。 无论GUID是否匹配,我们总是想设置版本。(情况如何)

这是编码

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) // this the if loop we need to concentrate { SpoDebug.DebugTraceSevere(func, "Unable to find ResourcePolicy with GUID: " + policyGuid); } else { // Search for the specified host foreach (DataModelObject dmo in allObjects) { if (dmo is IResourcePolicy) { if (string.Compare(dmo.Name, hostName, true) == 0) { IResourcePolicy irp = (IResourcePolicy)dmo; irp.ResourcePolicy = rp; irp.AgentPolicyVersion.Version = Convert.ToInt64(policyVersion); irp.ResourcePolicyEnabled = Convert.ToBoolean(enabled); irp.AgentVersion = agentVersion; 

所以我做了什么我做了赋值(irp.AgentVersion = agentVersion;)外面的if循环(if(rp == null))

像这样, 但我没有获得版本价值

 foreach (DataModelObject dmo in allObjects) { if (dmo is IResourcePolicy) { if (string.Compare(dmo.Name, hostName, true) == 0) { irp.AgentVersion = agentVersion; } 

任何人都可以建议我在这里做什么

我想你的意思是:

 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); } if (rp == null) // this the if loop we need to concentrate { 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) { irp.ResourcePolicy = rp; irp.AgentPolicyVersion.Version = Convert.ToInt64(policyVersion); irp.ResourcePolicyEnabled = Convert.ToBoolean(enabled); } // ... } } 

我已经删除了else位,所以循环总是被执行,然后在循环内添加if (rp != null) ,阻止它的某些部分执行。 那样你就不必复制循环代码了,我认为你在做什么?