2012-07-26 59 views
-1

我真的被困在這裏,並會很感激幫助。我創建了服務的請求數據合同和響應數據合同。請求DTO包含Cardnum,Id和Noteline1 ---- noteline18。響應DTO包含noteline1 - noteline18。如何根據c中的長度將字符串拆分爲數組#

我將字符串長度爲100的字符串傳遞給請求數據成員noteLine1(數據長度爲78個字符)。現在我想確保只有78個字符應該填充到noteline1數據成員中,其餘的應該放入請求DTO的另一個空的noteline數據成員中。我用下面的代碼,它爲我工作得很好:

string requestNoteReason = request.noteLine1; 
if (response != null) 
{ 
    foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo) 
    { 
     if (reqPropertyInfo.Name.Contains("noteLine")) 
     { 
      if (reqPropertyInfo.Name.ToLower() == ("noteline" + i)) 
      { 
       if (requestNoteReason.Length < 78) 
       { 
        reqPropertyInfo.SetValue(request, requestNoteReason, null); 
        break; 
       } 
       else 
       { 
        reqPropertyInfo.SetValue(request, requestNoteReason.Substring(0, 78), null); 
        requestNoteReason = requestNoteReason.Substring(78, requestNoteReason.Length - 78); 
        i++; 
        continue; 
       } 
      } 
     } 
    } 
    goto Finish; 
} 

現在我想的是包含超過78字符長度的字符串noteline1應該分裂,並得到填補在未來空noteline。如果字符串超過200個字符長度,那麼它應該拆分字符串並將其填充到下一個連續的空白noteline中。例如,如果字符串需要3個空白noteline的空間,那麼它應該只填充下一個連續可用空白noteline(即noteline2,noteline3,noteline4)中剩餘的字符串,並且不應該用已經存在的字符串填充noteline之前填充。

請幫

+0

有一個在代碼中的箭頭反模式和有goto語句,它不應該被用來 – Giedrius 2012-07-26 06:18:48

+0

goto語句有別的意思。我沒有在這裏寫過這些代碼。我只寫了需要實現的代碼 – 2012-07-26 06:23:44

+0

我只是好奇:爲什麼你使用noteline1..noteline18屬性而不是使用字符串數組? – 2012-07-26 08:33:39

回答

1
[TestFixture] 
public class Test 
{ 
    [Test] 
    public void TestLongLength() 
    { 
     var s = new string('0', 78) + new string('1', 78) + new string('2', 42); 
     var testClass = new TestClass(); 
     FillNoteProperties(s, testClass); 

     Assert.AreEqual(new string('0', 78), testClass.NoteLine1); 
     Assert.AreEqual(new string('1', 78), testClass.NoteLine2); 
     Assert.AreEqual(new string('2', 42), testClass.NoteLine3); 
    } 

    public static void FillNoteProperties(string note, TestClass testClass) 
    { 
     var properties = testClass.GetType().GetProperties(); 
     var noteProperties = (from noteProperty in properties 
           where noteProperty.Name.StartsWith("NoteLine", StringComparison.OrdinalIgnoreCase) 
           orderby noteProperty.Name.Length, noteProperty.Name 
           select noteProperty).ToList();     
     var i = 0; 
     while (note.Length > 78) 
     { 
      noteProperties[i].SetValue(testClass, note.Substring(0, 78), null); 
      note = note.Substring(78); 
      i++; 
     } 

     noteProperties[i].SetValue(testClass, note, null); 
    } 
} 
+0

一個不好的問題的好答案 – 2012-11-06 18:25:39

相關問題