【问题标题】:Accessing Anonymous Types in C# ArrayList在 C# ArrayList 中访问匿名类型
【发布时间】:2018-10-29 20:21:30
【问题描述】:

我有简单的 C# ArrayList:

 ArrayList sapTestData;
 sapTestData = new ArrayList();

我添加元素:

sapTestData.Add(new { Value = loanId, Text = description });

然而,当我尝试访问 sapTestData 时,使用

string test = sapTestData[1].Value;

我得到一个“对象”不包含“值”的定义......错误......

什么问题?

【问题讨论】:

  • 永远不要使用ArrayList。使用List<T> 以便您的集合可以静态类型化。
  • Cast to Anonymous Type的可能重复
  • 您打算在收藏中存储什么?它们都是同一类型吗?还是混合?你必须使用匿名类型吗?即使是List<object> 也比ArrayList 更容易处理。
  • 如果你真的希望列表是匿名的,你可以试试 var sapTestData = new List();

标签: c# arraylist


【解决方案1】:

您可以简单地使用泛型。

有一个像这样的对象:

var Loan = new { Value = “Loan1”, Text = description };

像这样添加到列表中:

var loanList = GetLoanList(Loan);

像下面这样访问它:

if(loanList.Any(n => n.Value == "Loan1"))
{
    Console.WriteLine("Loan 1 is there");
}

有如下方法:

public List<T> GetLoanList<T>(T item)
{
    List<T> newLoanList = new List<T>();
    newLoanList.Add(item);
    return newLoanList;
}     

var 在 C# 中是一个很棒的功能,但有时在类似这些推断的代码中是可取的。

【讨论】:

  • 我希望GetLoanList(item) 返回一个包含item 的列表。
  • 是的,它返回一个包含一个项目的列表..编辑了代码。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多