建造者模式读取数据

突然想起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; }
 }
posted @ 2024-07-30 14:41  孤沉  阅读(3)  评论(0编辑  收藏  举报