摘自微软的.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);