长?” 真的是一个结构吗?

sin*_*rix 5 c# nullable

根据定义 Nullable<> 是一个结构体,但是当我调用一些通用函数时,它的行为就像一个对象。

class GenController
{
    public void Get<T>(T id) where T : struct
    {
        Console.Write("is struct");
    }

    public void Get(object obj)
    {
        Console.Write("is object");
    }
}

long param1 = 1234;
new GenController().Get(param1);
// output is "is struct" as expected

long? param2 = 1234;
new GenController().Get(param2);
// output is "is object"
// obj seen at debug time as "object {long}"
// expected "is struct"
Run Code Online (Sandbox Code Playgroud)

所以参数被看作是一个对象而不是一个结构体。

知道发生了什么,我误解了的意思struct吗?

有没有一种方法来dispachNullable<T>Tobject不同类型的参数?

can*_*on7 6

Nullable<T>绝对是一个结构

您的问题更多是关于where T : struct泛型类型约束,而不是关于Nullable<T>.

文档

where T : struct:类型参数必须是不可为空的值类型。

long?可空值类型,因此where T : struct约束不允许。


The*_*aot 5

要回答这个问题:

  • Nullable<T> 是一个 struct
  • struct约束只允许不可为空的结构。

话虽如此,您可以指定参数可为空,如下所示:

public void Get<T>(T? id)
    where T: struct
{
    Console.Write("is nullable struct");
}
Run Code Online (Sandbox Code Playgroud)

这将是捕获可为空结构的另一种重载。