[英]C# Custom generic struct with same compiler behavior as Nullable<T>
Behold the following example with System.Nullable<T>
in C#. 用C#中的System.Nullable<T>
看下面的示例。
int x = 5;
int? y = 3;
int? result = x + y; //no compiler warning
It makes sense that the compiler can figure out that T
is an int
, thus it can use the operator. 编译器可以确定T
是一个int
,因此可以使用运算符,这是有道理的。
Also in 同样在
int x = 5;
int? y = 3;
bool result = x == y; //no compiler warning
it makes sense, if x
was null
, the expression would be false
. 这是有道理的,如果x
为null
,则表达式将为false
。 The compiler doesn't mind. 编译器不在乎。
Now I'm trying to create a lookalike Nullable<T>
class. 现在,我试图创建一个类似的Nullable<T>
类。 Let's call it Lookable<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;
}
}
The idea here is straight from .NET's source code . 这里的想法直接来自.NET的源代码 。 In my case I'm just omitting the HasValue
property. 就我而言,我只是省略了HasValue
属性。 Now this example would work: 现在,此示例将起作用:
int x = 6;
Lookable<int> y = x;
Lookable<int> z = 4;
The compiler can infer the types here because of the implicit operator
correct? 编译器可以在这里推断类型,因为implicit operator
正确吗?
What I don't understand is that this example will make the compiler unhappy: 我不明白的是,此示例会使编译器不满意:
int x = 5;
Lookable<int> y = 3;
var result1 = x + y; //compile error
var result2 = x == y; //compile error
The compiler is giving me the message: 编译器给我消息:
Operator cannot be applied to operands of type '
int
' and 'Lookable<int>
'. 运算符不能应用于类型为'int
'和'Lookable<int>
'的操作数。
Why not? 为什么不? And why is it possible with Nullable<T>
? 以及为什么可以使用Nullable<T>
呢? I can't find it anywhere in the source code. 我在源代码的任何地方都找不到它。 Would it also be possible for Lookable<T>
? Lookable<T>
是否也可能?
The code for this isn't in Nullable<T>
- it is in the C# compiler, in particular "lifted operators" in the specification, and how they apply specifically to System.Nullable<T>
. 此代码不在Nullable<T>
,而是在C#编译器中,尤其是在规范中的“提升运算符”中,以及它们如何专门应用于System.Nullable<T>
。 The specification references are in this answer . 规范参考在此答案中 。
You cannot reproduce the Nullable<T>
behaviour in your own types. 您不能以自己的类型重现Nullable<T>
行为。 It has special handling by both the compiler and the runtime (boxing, etc). 它具有编译器和运行时的特殊处理(装箱等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.