C#实现定义一个通用返回值

 

场景

很多情况下,我们在使用函数的时候,需要return多个返回值,比如说需要获取处理的状态以及信息、结果集等。最古老的时候,有用ref或者out来处理这个情况,但是需要定义处理等操作之类的,而且书写也不是很舒服,感觉就是不太完美;后来有了dynamic后,觉得也是个不错的选择,可惜也有很多局限性,比如:匿名类无法序列化、返回结果不够直观等。再然后就写一个结构化的对象来接收,但是如果每个方法都定义一个对象去接收的话,想必也会很麻烦;

 

需求

所以,综上场景所述,我们可以写一个比较通用的返回值对象,然后使用泛型来传递需要return的数据。

 

开发环境

.NET Framework版本:4.5

 

开发工具

Visual Studio 2013

 

实现代码

[Serializable]
  public class ReturnResult
  {
      public ReturnResult(Result _result, string _msg)
      {
          this.result = _result;
          this.msg = _result == Result.success ? "操作成功!" + _msg : "操作失败!" + _msg;
      }
      public ReturnResult(Result _result)
          : this(_result, "")
      {
      }
      public Result result { get; set; }
      public string msg { get; set; }
  }
  [Serializable]
  public class ReturnResult<T> : ReturnResult
  {
      public ReturnResult(T _data)
          : base(Result.success)
      {
          this.data = _data;
      }
      public ReturnResult(Result _result, string _msg)
          : base(_result, _msg)
      {
      }
      public ReturnResult(Result _result, string _msg, T _data)
          : base(_result, _msg)
      {
          this.data = _data;
      }
      public T data { get; set; }
  }

  public enum Result
  {
      error = 0,
      success = 1
  }
public ReturnResult<string> GetMsg()
      {
          return new ReturnResult<string>("msg");
      }
      public ReturnResult<int> GetCode()
      {
          return new ReturnResult<int>(10);
      }
      public ReturnResult<Student> GetInfo()
      {
          Student student = new Student
          {
              id = 1,
              name = "张三"
          };
          return new ReturnResult<Student>(student);
      }

      public class Student
      {
          public int id { get; set; }
          public string name { get; set; }
      }

      private void button1_Click(object sender, EventArgs e)
      {
          var result = GetCode();
          if (result.result == Result.success)
          {
              MessageBox.Show(result.msg + result.data);
          }
      }

      private void button2_Click(object sender, EventArgs e)
      {
          var result = GetMsg();
          if (result.result == Result.success)
          {
              MessageBox.Show(result.msg + result.data);
          }
      }

      private void button3_Click(object sender, EventArgs e)
      {
          var result = GetInfo();
          if (result.result == Result.success)
          {
              MessageBox.Show(result.msg + Newtonsoft.Json.JsonConvert.SerializeObject(result.data));
          }
      }

 

实现效果

代码解析:挺简单的,也没啥可解释的。

关于C#实现定义一个通用返回值的文章就介绍至此,更多相关C#通用返回值内容请搜索编程宝库以前的文章,希望以后支持编程宝库

对集合排序,可能最先想到的是使用OrderBy方法。 class Program { static void Main(string[] args) { IEnumerable<Student ...