如果数组有未设置的值,如何设置返回值
本文关键字:设置 何设置 返回值 数组 如果 | 更新日期: 2023-09-27 18:02:46
我有一个这样的代码
int rpindex = allObjects.Find(new Guid(policyGuid));
if (rpindex != -1)
{
rp = (ResourcePolicy)allObjects.GetAt(rpindex);
}
,这是查找方法
public virtual int Find(Guid guid)
{
try
{
for (int i=0; i<this.Count; i++)
{
if (guid.Equals(this[i].Guid))
{
return i;
}
}
}
catch(System.Exception exception)
{
SpoDebug.DebugTraceSevere(func, "Exception Occurred: " + exception.ToString() );
}
SpoDebug.DebugTraceVerbose(func, "no find. guid=" + guid.ToString());
return -1;
}
到目前为止,现有函数Find()的结果是-1或某个整数值[i]。-1值将在两种情况下出现,即如果输入为空[空值],如果输入是一些不在数据库或当前列表中的值,我需要在这里更改。这意味着,如果Find()的输入是空的或空的,只有一次它应该返回-1,否则,如果输入有一些值,它不是机器处理,那么它应该返回-2。所以应该有三个结果,一个是-1,第二个是-2,第三个是整数值,有人能告诉我吗如果我添加else循环,我不确定这里除了-1和整数值
只是放置额外的返回语句,还是我错过了什么?
。
try
{
for (int i=0; i<this.Count; i++)
{
if (guid.Equals(this[i].Guid))
{
return i;
}
}
return somethingElseHere;
}
就在for循环检查之后
if(i == this.Count) //i reached the end of the loop but no matches found
{
return -2;
}
我认为在列表为空的情况下抛出一个异常会更容易读,就在方法开始之后:
if (this.Count==0)
throw new InvalidArgumentException();
//rest as before