Реализация интерфейса - C# (179705)

Узнай цену своей работы

Формулировка задачи:

Написал пример из книги O'Reilly Learning C# 3.0 Chapter 18 создание File-Copier. Все сделал "по инструкции" и несколько раз перепроверил код, но работает с ошибками (их очень много), но хотел бы разобраться хотя бы по основным вопросам, указанных в комментариях (или подскажите где можно почитать): 1. fileList.Sort(comparer);//Почему мы здесь передаем ссылку на объект, в котором реализована только одна ф-ия Compaprer, а не на саму функцию - comparer.Comparer(file1, file2)? Она же не должна вызываться сама по себе.. Как это возможно? (153 строка) 2. public int Comparer(FileInfo file1, FileInfo file2)// почему компилятор не видит здесь реализацию интерфейса? //пробовал изменить название на IComparer<FileInfo>.Comparer, но безуспешно... Почему? (173)
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.IO;
  11. namespace File_Copier
  12. {
  13. public partial class FrmFileCopier : Form
  14. {
  15. private const int MaxLevel = 2;
  16. public FrmFileCopier()
  17. {
  18. InitializeComponent();
  19. FillDirectoryTree(tvwSource, true);
  20. FillDirectoryTree(tvwTargetDir, false);
  21. }
  22. private void FillDirectoryTree(TreeView tvw, bool isSource)
  23. {
  24. tvw.Nodes.Clear();
  25. string[] strDrives = Environment.GetLogicalDrives();
  26. foreach(string rootDirectoryName in strDrives)
  27. {
  28. try
  29. {
  30. DirectoryInfo dir = new DirectoryInfo(rootDirectoryName);
  31. dir.GetDirectories();
  32. TreeNode ndRoot = new TreeNode(rootDirectoryName);//create ndRoot to hold the directories
  33. tvw.Nodes.Add(ndRoot);
  34. if (isSource) { GetSubDirectoryNodes(ndRoot, ndRoot.Text, true, 1); }
  35. else { GetSubDirectoryNodes(ndRoot, ndRoot.Text, false, 1); }
  36. }
  37. catch { }
  38. Application.DoEvents();
  39. }
  40. }
  41. private void GetSubDirectoryNodes(TreeNode parentNode, string fullName, bool getFileNames, int level)
  42. {
  43. DirectoryInfo dir = new DirectoryInfo(fullName);
  44. DirectoryInfo[] dirSubs = dir.GetDirectories();
  45. foreach(DirectoryInfo dirSub in dirSubs)
  46. {
  47. if ((dirSub.Attributes & FileAttributes.Hidden) != 0) { continue; }
  48. TreeNode subNode = new TreeNode(dirSub.Name);
  49. parentNode.Nodes.Add(subNode);
  50. if (level < MaxLevel)
  51. {
  52. GetSubDirectoryNodes(subNode, dirSub.FullName, getFileNames, level + 1);
  53. }
  54. if (getFileNames)
  55. {
  56. FileInfo[] files = dir.GetFiles();
  57. foreach(FileInfo file in files)
  58. {
  59. TreeNode fileNode = new TreeNode(file.Name);
  60. parentNode.Nodes.Add(fileNode);
  61. }
  62. }
  63. }
  64. }
  65. private void label1_Click(object sender, EventArgs e)
  66. {
  67. }
  68. private void tvwSource_AfterCheck(object sender, TreeViewEventArgs e)
  69. {
  70. SetCheck(e.Node, e.Node.Checked);
  71. }
  72. private void SetCheck(TreeNode node, bool check)
  73. {
  74. foreach(TreeNode n in node.Nodes)
  75. {
  76. n.Checked = check; //check the node
  77. if (n.Nodes.Count != 0) { SetCheck(n, check); }
  78. }
  79. }
  80. private void tvwSource_BeforeExpand(object sender, TreeViewCancelEventArgs e)
  81. {
  82. tvwExpand(sender, e.Node);
  83. }
  84. private void tvwExpand(object sender, TreeNode currentNode)
  85. {
  86. TreeView tvw = (TreeView)sender;
  87. bool getFiles = (tvw == tvwSource);
  88. string fullName = currentNode.FullPath;
  89. currentNode.Nodes.Clear();
  90. GetSubDirectoryNodes(currentNode, fullName, getFiles, 1);
  91. }
  92. private void tvwTargetDir_BeforeExpand(object sender, TreeViewCancelEventArgs e)
  93. {
  94. tvwExpand(sender, e.Node);
  95. }
  96. private void tvwTargetDir_AfterSelect(object sender, TreeViewEventArgs e)
  97. {
  98. string theFullPath = e.Node.FullPath;
  99. if (theFullPath.EndsWith(""))
  100. {
  101. theFullPath = theFullPath.Substring(0, theFullPath.Length - 1);
  102. }
  103. txtTargetDir.Text = theFullPath;
  104. }
  105. private void btnClear_Click(object sender, EventArgs e)
  106. {
  107. foreach(TreeNode node in tvwSource.Nodes) { SetCheck(node, false); }
  108. }
  109. private void btnCopy_Click(object sender, EventArgs e)
  110. {
  111. List<FileInfo> fileList = GetFileList();
  112. foreach(FileInfo file in fileList)
  113. {
  114. try
  115. {
  116. lblStatus.Text = "Copying " + txtTargetDir.Text + "" + file.Name + "...";
  117. Application.DoEvents();
  118. file.CopyTo(txtTargetDir.Text + "" + file.Name, chkOverwrite.Checked);
  119. }
  120. catch(Exception ex) { MessageBox.Show(ex.Message); }
  121. }
  122. lblStatus.Text = "Done.";
  123. //Application.DoEvents();
  124. }
  125. private List<FileInfo> GetFileList()
  126. {
  127. List<string> fileNames = new List<string>();
  128. foreach(TreeNode theNode in tvwSource.Nodes)
  129. {
  130. GetCheckedFiles(theNode, fileNames);
  131. }
  132. List<FileInfo> fileList = new List<FileInfo>();
  133. foreach(string fileName in fileNames)
  134. {
  135. FileInfo file = new FileInfo(fileName);
  136. if (file.Exists) { fileList.Add(file); }
  137. }
  138. IComparer<FileInfo> comparer = (IComparer<FileInfo>) new FileComparer();// создаем интерфейсную ссылку на объект класса
  139. fileList.Sort(comparer);//Почему мы здесь передаем ссылку на объект, в котором реализована только одна ф-ия
  140. //Compaprer, а не на саму функцию? Она же не вызывается сама по себе...
  141. return fileList;
  142. }
  143. private void GetCheckedFiles(TreeNode node, List<string> fileNames)
  144. {
  145. if(node.Nodes.Count==0)//if this is a leaf...
  146. {
  147. if(node.Checked)//if the node was checked...
  148. {
  149. fileNames.Add(node.FullPath);//if the node was checked...
  150. }
  151. }
  152. else
  153. {
  154. foreach(TreeNode n in node.Nodes) { GetCheckedFiles(n, fileNames); }
  155. }
  156. }
  157. public class FileComparer: IComparer<FileInfo>
  158. {
  159. public int Comparer(FileInfo file1, FileInfo file2)// почему компилятор не видит здесь реализацию интерфейса?
  160. //пробовал изменить название на IComparer<FileInfo>.Comparer, но безуспешно... Почему?
  161. {
  162. if (file1.Length > file2.Length) { return -1; }
  163. if (file1.Length < file2.Length) { return 1; }
  164. return 0;
  165. }
  166. int IComparer<FileInfo>.Compare(FileInfo x, FileInfo y)// этой функции в примере нет, но без нее не работает -
  167. // не реализован интерфейс
  168. {
  169. throw new NotImplementedException();
  170. }
  171. }
  172. private void btnDelete_Click(object sender, EventArgs e)
  173. {
  174. System.Windows.Forms.DialogResult result =
  175. MessageBox.Show(
  176. "Are you quite sure?",
  177. "Delete Files",
  178. MessageBoxButtons.OKCancel,
  179. MessageBoxIcon.Exclamation,
  180. MessageBoxDefaultButton.Button2);
  181. if(result== System.Windows.Forms.DialogResult.OK)
  182. {
  183. List<FileInfo> fileNames = GetFileList();
  184. foreach (FileInfo file in fileNames)
  185. {
  186. try
  187. {
  188. lblStatus.Text = "Deleting " + txtTargetDir.Text + "" + file.Name + "...";
  189. Application.DoEvents();
  190. file.Delete();
  191. }
  192. catch (Exception ex) { MessageBox.Show(ex.Message); }
  193. }
  194. lblStatus.Text = "Done.";
  195. Application.DoEvents();
  196. }
  197. }
  198. private void btnCancel_Click(object sender, EventArgs e)
  199. {
  200. Application.Exit();
  201. }
  202. }
  203. }

Решение задачи: «Реализация интерфейса»

textual
Листинг программы
  1. void Sort(IComparer comparer)
  2. {
  3. ...
  4.     int result = comparer.Compare(arr[i], arr[j]);
  5. ...
  6. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 4.286 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут