_value是个结构体,是传入的T范型,这里是return它的Value属性。
lambda表达式,定义的是那个运算符的返回值
这个地方是要用value.Value才对,之前我看得不够仔细,跟你说错了。
public static explicit operator T(Nullable<T> value) => value.Value;
用自己写的Struct的时候,下面两句跑不过去是正常的,只有System.Nullable才可以这样干。
都是编译器和CLR完成的。
x += 3;
x = null;
当使用System.Nullable的时候,其实用到的都是lifted operator去完成System.Nullable的计算。
x = null编译的时候会变成x = new System.Nullable()。
当然如果一定要想做加法也不是绝对不行,就需要自己再写个加法的operator。
下面的代码,你可以跑一下试试。
using System;
namespace ConsoleApp1
{
class Program
{
public struct Nullable<T>
where T:struct
{
public Nullable(T value)
{
_hasValue = true;
_value = value;
}
private bool _hasValue;
public bool HasValue => _hasValue;
private T _value;
public T Value
{
get
{
if(!_hasValue)
{
throw new InvalidOperationException("no value");
}
return _value;
}
}
public static explicit operator T(Nullable<T> value) {
Console.WriteLine("operator => Convert explicitly.");
return value.Value;
}
public static implicit operator Nullable<T>(T value) {
Console.WriteLine("operator => Convert implicitly.");
return new Nullable<T>(value);
}
public static Nullable<T> operator + (Nullable<T> value1, int value2)
{
dynamic _value = value1.Value;
return new Nullable<T>(_value+value2);
}
public override string ToString() => !HasValue ? string.Empty : _value.ToString();
}
static void Main(string[] args)
{
Nullable<int> x;
Console.WriteLine("start");
x = 4;
Console.WriteLine("x:" + x);
int i = (int)x;
Console.WriteLine("i:" + i);
x+=3;
Console.WriteLine(x);
if(x.HasValue)
{
int y = x.Value;
}
// x = null;
}
}
}
using System;
namespace ConsoleApp1
{
class Program
{
public struct Nullable<T>
where T:struct
{
public Nullable(T value)
{
_hasValue = true;
_value = value;
}
private bool _hasValue;
public bool HasValue => _hasValue;
private T _value;
public T Value
{
get
{
if(!_hasValue)
{
throw new InvalidOperationException("no value");
}
return _value;
}
}
public static explicit operator T(Nullable<T> value) => _value.Value;
public static implicit operator Nullable<T>(T value) => new Nullable<T>(value);
public override string ToString() => !HasValue ? string.Empty : _value.ToString();
}
static void Main(string[] args)
{
Nullable<int> x;
x = 4;
x += 3;
if(x.HasValue)
{
int y = x.Value;
}
x = null;
}
}
}
这里就直接报错了