![](/img/trans.png)
[英]How to setup MVC mock.Setup and.Returns for a repository method, which has on out parameter and a return type
[英]How to break out a program flow of a method that returns a different type?
我遇到了一個特別棘手的問題,如果我的代碼失敗,我需要中斷我的代碼,但是我的以下方法希望將Arraylist作為返回,而不僅僅是正常的“ return”,我該如何解決?
public ArrayList ReadCLientDetailsFromFile(string clientCsvfileName)
{
List<string> numbersFromTheFile = new List<string>();
using (StreamReader file = File.OpenText(clientCsvfileName))
{
int lineCount = 0;
while (!file.EndOfStream)
{
Client client = new Client();
lineCount++;
string lineFromFile = file.ReadLine();
string [] strValue = lineFromFile.Split(';');
var commas = strValue.Count();
if (commas < 3 || commas >4)
{
MessageBox.Show("There is more than 4 values on line "+ lineCount + "\nThe Operation will abort");
break; //exit the code here
}
else
{
client.clientCode = strValue[0];
client.depositId4 = strValue[1];
client.depositId5 = strValue[2];
client.errorType = strValue[3];
//put initial checks checks here and set defaults. 0
_clientCollectionList.Add(client);
}
}
MessageBox.Show(_clientCollectionList.Count.ToString());
return _clientCollectionList;
}
}
公共ArrayList ReadCLientDetailsFromFile(string clientCsvfileName)
仍然使用ArrayList
,這是.Net 1. +版本,此后被List<T>
和引入的許多其他數據結構所取代,時間與當今的.Net框架保持一致,該框架僅領先15年以上。
關於你的問題
它只需要一個返回值,只需創建一個返回值,如果沒有值被填充或沒有顯式初始化(如果您有_clientCollectionList
,則可以返回默認值,如null),但是在哪里初始化,簡單返回與默認/當前值相同,這全都與代碼編譯有關
最常規的方法是從遇到錯誤的地方引發異常並在代碼中處理該異常,該異常會調用該方法
public ArrayList ReadCLientDetailsFromFile(string clientCsvfileName)
{
//some code
if (commas < 3 || commas >4)
{
MessageBox.Show("There are more than 4 values on line "+ lineCount + "\nThe
Operation will abort");
throw new ArgumentOutOfRangeException("There is more than 4 values on line "+
lineCount); //exit the code here
}
//rest of the code
}
並在調用代碼中:
try
{
ArrayList clientDetails = ReadCLientDetailsFromFile(clientCsvfileName);
}
catch
{
//some exception handling
}
另一種方法是將ArrayList作為參數傳遞給您的方法,並使方法在成功/失敗時返回bool
public bool TryReadCLientDetailsFromFile(ArrayList dest, string clientCsvfileName)
{
//some logic
if (commas < 3 || commas >4)
{
MessageBox.Show("There is more than 4 values on line "+ lineCount + "\nThe Operation will abort");
return false //exit the code here
}
//rest of the logic, sussess
return true
}
在這里您有2個可用選項
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.