垃圾站 网站优化 C#实现定义一个通用返回值

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

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

需求

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

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

开发环境

.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#实现定义一个通用返回值插图1

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

上一篇
下一篇
联系我们

联系我们

返回顶部