简体   繁体   English

C#通用列表

[英]c# Generic List

I m populating data for different entities into set of lists using generic lists as follows : 我使用通用列表将不同实体的数据填充到列表集中,如下所示:

List<Foo> foos ..
List<Bar> bars ..

I need to write these lists to a file, i do have a util method to get the values of properties etc. using reflection. 我需要将这些列表写入文件,我确实有一个util方法来使用反射来获取属性等的值。

What i want to do is: using a single method to write these into files such as: 我想要做的是:使用一种方法将这些内容写入文件,例如:

 void writeToFile(a generic list)
 {
  //Which i will write to file here.
 }

How can i do this? 我怎样才能做到这一点?

I want to be able to call : 我希望能够打电话给:

writeToFile(bars);
writeToFile(foos);
void writeToFile<T>(List<T> list)
{
    // Do the writing
}

You can use generics to allow the caller to specify the expected type the list contains. 您可以使用泛型来允许调用方指定列表包含的预期类型。

void writeToFile<T>(IList<T> list)
{
    ...
}

Probably something like... 大概像...

private void WriteToFile<T>(
  IEnumerable<T> elementsToWrite,
  Func<T, string> convertElementToString) {
  foreach (var element in elementsToWrite)
  {
    var stringRepresentation = convertElementToString(element);
    // do whatever other list-stuff you need to do
  }
}

// called like so...
WriteToFile(listOfFoo, foo => foo.FP1 + ", " + foo.FP2 + " = " foo.FP3);
WriteToFile(listOfBar, bar => bar.BP1 +"/"+ bar.BP2 + "[@x='" + bar.BP3 + "']");

...or you could try something like... ...或者您可以尝试类似...

private void WriteToFile<T>(
  IEnumerable<T> elementsToWrite,
  Action<T, TextWriter> writeElement) {
  var writer = ...;

  foreach (var element in elementsToWrite)
  {
    // do whatever you do before you write an element
    writeElement(element, writer);
    // do whatever you do after you write an element
  }
}

// called like so...
WriteToFile(listOfFoo, (foo, writer) =>
  writer.Write("{0}, {1} = {2}", foo.FP1, foo.FP2, foo.FP3));
WriteToFile(listOfBar, (bar, writer) =>
  writer.Write("{0}/{1}[@x='{2}']", bar.BP1, bar.BP2, bar.BP3));

...or whatever... you get the idea. ...或任何...您有主意。

You should look into the topic of serialization . 您应该研究序列化主题。 There is are some articles out there about dealing with generic types. 还有就是有一些 文章在那里关于处理泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM