建造者模式讀取資料

孤沉發表於2024-07-30

突然想起Asp.Net 啟動專案的建造者寫法非常優秀,所以讓自己的程式碼看起來高階,美觀,優雅。
我模擬一個場景使用它
直接上程式碼

 public class TestQuery
 {     
     public static void Main()
     {
         QueryableBuilder queryableBuilder = new QueryableBuilder();
         queryableBuilder.Queryable.LoadFile(() => 
         {
             var file = new MyFile()
             {
                 Path="E://測試.txt"
             };
             return file;
         });
     }
     public static async Task MainAsync()
     {
         QueryableBuilder queryableBuilder = new QueryableBuilder();
         string result = await queryableBuilder.Queryable.LoadFileAsync(() =>
         {
             var file = new MyFile()
             {
                 Path = "E://測試.txt"
             };
             return file;
         });
     }
}
 public class FileQueryable
 {
     public string LoadFile(Func<MyFile> func)
     {
         MyFile file=func.Invoke();
         StreamReader reader = new StreamReader(file.Path);
         var result=reader.ReadToEnd();           
         return result;
     }
     public async Task<string> LoadFileAsync(Func<MyFile> func)
     {
         MyFile file = func.Invoke();
         using (StreamReader reader = new StreamReader(file.Path))
         {
             var result = await reader.ReadToEndAsync();
             return result;
         }
     }
 }

 public class MyFile
 {
     public string Name { get; set; }
     public string Path { get; set; }
 }

相關文章