日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#實現定義一個通用返回值_C#教程

作者:Csharp小記 ? 更新時間: 2022-11-13 編程語言

場景

很多情況下,我們在使用函數的時候,需要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));
            }
        }

實現效果

代碼解析:挺簡單的,也沒啥可解釋的。

原文鏈接:https://mp.weixin.qq.com/s/rUvJrdFcBJtMBYPMjgOAOw

欄目分類
最近更新