类中的列表字符串
本文关键字:字符串 列表 | 更新日期: 2023-09-27 18:19:19
我有一个有几个public accessor
的类,其中一个是List<String> p {get; set;}
我的问题是:
在实例化该类的代码中,我正在循环通过一个字符串,该字符串可以包含许多行p,因此对于每一行p,我想将其添加到List<String> p
所以我试过了:
instancenam.p.AddRange(string.Split(new char[] {':',':'})[2]);
使我在字符串中获得第二组值,如:23A:TETCGR
当我运行代码时,我得到以下两个错误:
错误1:
最佳重载方法匹配' system . collections . generic . list . adrange (System.Collections.Generic.IEnumerable)'有一些无效参数
错误2:
参数1:不能从'string'转换为'System.Collections.Generic.IEnumerable'*
我已经用谷歌搜索过了,但是对回答感到困惑;-)
foreach (string STR in lines){//检查长度是否大于3。If (str != "4:" &&STR != " "){//存储标签名
if (str.StartsWith(":"))
{
tag = str.Split(new char[] { ':', ':' })[1];
SavedTag = tag;
switch (MessageType)
{
// Tag 13C Time Indication
if (tag == "13C")
{
mt202.tag13C.Add(str.Split(new char[] { ':', ':' })[2]);
}
break;
}
好的,所以命名为推荐,我现在有以下内容。其中我的字符串包含多个标签:13C:
使用上面的添加i获取对象引用不设置为对象的实例
编辑: public class MT202
{
public string tag20 { get; set; }
public string tag21 { get; set; }
public List<String> tag13C { get; set; }
public string tag32A { get; set; }
public string tag33B { get; set; }
}
// Code below is from the calling class
if (tag == "13C")
{
char[] delimiters = new char[] { ':', ':' };
string[] splitValues = str.Split(delimiters);
string singleValue = splitValues[2];
List<string> mt202.tag13C = new List<string>();
mt202.tag13C.Add(singleValue);
// mt202.tag13C.Add(str.Split(new char[] { ':', ':' })[2]);
}
让我们分解这一行:
instancenam.p.AddRange(string.Split(new char[] {':',':'})[2]);
我将假设string
部分实际上是变量的名称(string
不是有效的标识符)。我把它命名为text
。
展开后的代码如下:
char[] delimiters = new char[] {':',':'};
string[] splitValues = text.Split(delimiters);
string singleValue = splitValues[2];
List<string> list = instancenam.p;
list.AddRange(singleValue);
这将给出相同的错误,因为你正在调用AddRange
,这意味着采取集合值-但你只提供一个单个值。如果您只想添加单个值,请使用Add
:
instancenam.p.Add(text.Split(new char[] {':',':'})[2]);
我建议将代码分解成一个位的东西,更像上面的代码——可能没有分解到那么远,但至少有一点。(您可以为分隔符设置一个只读静态字段,作为开始。)
此外,我强烈建议您将您的属性从p
重命名为更有意义的东西,在PascalCase中符合。net命名约定。
编辑:现在这篇文章已经被编辑成:
使用上面的添加i获取对象引用不设置为对象的实例
这表明mt202
或mt202.tag13C
是null
的引用,但我们不能分辨哪一个。