【问题标题】:Object not containing public definition for GetEnumerator, how can I iterate through the properties? [duplicate]对象不包含 GetEnumerator 的公共定义,如何遍历属性? [复制]
【发布时间】:2017-10-15 21:23:47
【问题描述】:

如何枚举FileInfo对象“info”的所有属性?

我在下面列出了他们的名字,但我无法用 foreach 循环或 for 循环枚举它们?谢谢

    string filePathAndName = "c:\temp.txt";

    FileInfo info = new FileInfo(filePathAndName);  
    // attributes, creation time, creation timeutc, directory, directoryname, exists, extension, fullname, isreadonly, lastaccesstime, lastaccesstimeutc, lastwritetime, lastwritetimeutc, length, name

【问题讨论】:

  • 您是在谈论文件系统所称的文件属性(存档、只读等)中的实际文件属性,还是FileInfo 属性?您需要注意术语以避免歧义。
  • 文件信息属性。下面的代码效果很好,我搜索了 2 个小时并没有找到。感谢回复

标签: c# loops


【解决方案1】:
var info = new FileInfo(filePathAndName);

foreach (var propertyInfo in info.GetType().GetProperties())
{
    Console.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(info)}");
}

【讨论】:

  • 感谢您提供有用的答案。既然我看到了您的答案是如何工作的,我就可以阅读上面更通用的答案并理解它是如何适用的。
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2014-07-10
  • 2014-04-24
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2013-02-16
  • 2021-10-18
相关资源
最近更新 更多