2012-07-26 50 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

相关问题