使用匿名类型和IComparable接口查找文件夹中最大的文件
本文关键字:文件夹 文件 查找 接口 类型 IComparable | 更新日期: 2023-09-27 18:19:56
在执行时,代码出现错误,我不知道在哪里必须进行更改才能实现接口。下面是我在控制台应用程序中尝试的完整代码
Error 1 'ConsoleApplication16.Temp' does not implement interface member 'System.IComparable<ConsoleApplication16.Temp>.CompareTo(ConsoleApplication16.Temp)' D:'nnn'ConsoleApplication16'ConsoleApplication16'Program.cs 32 18 ConsoleApplication16
下面是我的代码
class Program
{
static void Main()
{
string []files=Directory.GetFiles("C:''WINDOWS","*.*",SearchOption.AllDirectories);
Console.WriteLine(files.Count());
//Get Maximum
var max = (from fileName in files
let info = new FileInfo(fileName)
orderby info.Length descending
select new { FileName = info.Name, Size = info.Length })
.Take(1);
Console.WriteLine("Using Take : {0}",max.ElementAt(0));
//With anonymous Type we have to indicate what to get the max of
var max2 = (from fileName in files
let info = new FileInfo(fileName)
select
new Temp{ FileName = info.Name, Size = info.Length })
.Max(s => s.Size);
Console.WriteLine("Using Max:{0}", max2);
Console.ReadLine();
}
}
public class Temp : IComparable<Temp> //error is here
{
public string FileName { set; get; }
public long Size { set; get; }
public int compareTo(Temp o)
{
return Size.CompareTo(o.Size);
}
public override string ToString()
{
return string.Format("FileName:{0},Size:{1}", FileName, Size);
}
}
C#区分大小写,它是CompareTo
而不是compareTo
public int CompareTo(Temp o)
{
return Size.CompareTo(o.Size);
}
然而,我不知道这个编译器错误与代码的其余部分有什么关系,因为在LINQ查询中从未使用过CompareTo
。