C# 中有趣的重写

摘自微软的.net Core WebApi ActionResult

    当第一眼看到这个返回方式时很奇特 为毛线ActionResult<String> 能返回字符串? 碉堡了呀有木有,

抓紧看下他的实现方式是用的什么黑科技,当转入到引用里的时候发现自己有点营养跟不上了,原来是重写操作符。
平时很少用到重写操作符的model ,mmp 才发现重写操作符简直是装逼卖萌无所不能啊。


先看他的实现方式

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

看下他的声明

    //
    // 摘要:
    //     A type that wraps either an TValue instance or an Microsoft.AspNetCore.Mvc.ActionResult.
    //
    // 类型参数:
    //   TValue:
    //     The type of the result.
    public sealed class ActionResult<TValue> : IConvertToActionResult
    {
        //
        // 摘要:
        //     Initializes a new instance of Microsoft.AspNetCore.Mvc.ActionResult`1 using the
        //     specified value.
        //
        // 参数:
        //   value:
        //     The value.
        public ActionResult(TValue value);
        //
        // 摘要:
        //     Intializes a new instance of Microsoft.AspNetCore.Mvc.ActionResult`1 using the
        //     specified Microsoft.AspNetCore.Mvc.ActionResult.
        //
        // 参数:
        //   result:
        //     The Microsoft.AspNetCore.Mvc.ActionResult.
        public ActionResult(ActionResult result);

        //
        // 摘要:
        //     Gets the Microsoft.AspNetCore.Mvc.ActionResult.
        public ActionResult Result { get; }
        //
        // 摘要:
        //     Gets the value.
        public TValue Value { get; }

        public static implicit operator ActionResult<TValue>(TValue value);
        public static implicit operator ActionResult<TValue>(ActionResult result);
    }

写一个小例子

    public sealed class AnyResults<TValue>
    {
        public AnyResults(TValue value)
        {
            Values = new List<TValue>() { value };
        }

        public AnyResults(IEnumerable<TValue> values)
        {
            Values = new List<TValue>(values);
        }


        public static implicit operator AnyResults<TValue>(TValue value)
        {
            return new AnyResults<TValue>(value);
        }

        public static implicit operator AnyResults<TValue>(TValue[] results)
        {
            return new AnyResults<TValue>(results);
        }

        public override string ToString()
        {
            return Values.ToString();
        }

        public List<TValue> Values { get; }
    }

测试一下

            AnyResults<String> anyResults = "呵呵哒";
            Console.WriteLine(anyResults);
            anyResults = new String[] { "呵", "呵", "哒" };
            Console.WriteLine(anyResults);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值