[英]C# Custom generic struct with same compiler behavior as Nullable<T>
用C#中的System.Nullable<T>
看下面的示例。
int x = 5;
int? y = 3;
int? result = x + y; //no compiler warning
编译器可以确定T
是一个int
,因此可以使用运算符,这是有道理的。
同样在
int x = 5;
int? y = 3;
bool result = x == y; //no compiler warning
这是有道理的,如果x
为null
,则表达式将为false
。 编译器不在乎。
现在,我试图创建一个类似的Nullable<T>
类。 我们称之为Lookable<T>
。
[Serializable]
public struct Lookable<T> where T : struct
{
public Lookable(T value)
{
Value = value;
}
public T Value { get; }
public override bool Equals(object other)
{
return other != null && Value.Equals(other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value.ToString();
}
public static implicit operator Lookable<T>(T value)
{
return new Lookable<T>(value);
}
public static explicit operator T(Lookable<T> value)
{
return value.Value;
}
}
这里的想法直接来自.NET的源代码 。 就我而言,我只是省略了HasValue
属性。 现在,此示例将起作用:
int x = 6;
Lookable<int> y = x;
Lookable<int> z = 4;
编译器可以在这里推断类型,因为implicit operator
正确吗?
我不明白的是,此示例会使编译器不满意:
int x = 5;
Lookable<int> y = 3;
var result1 = x + y; //compile error
var result2 = x == y; //compile error
编译器给我消息:
运算符不能应用于类型为'
int
'和'Lookable<int>
'的操作数。
为什么不? 以及为什么可以使用Nullable<T>
呢? 我在源代码的任何地方都找不到它。 Lookable<T>
是否也可能?
此代码不在Nullable<T>
,而是在C#编译器中,尤其是在规范中的“提升运算符”中,以及它们如何专门应用于System.Nullable<T>
。 规范参考在此答案中 。
您不能以自己的类型重现Nullable<T>
行为。 它具有编译器和运行时的特殊处理(装箱等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.