根据定义 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>或T与object不同类型的参数?
要回答这个问题:
Nullable<T> 是一个 structstruct约束只允许不可为空的结构。话虽如此,您可以指定参数可为空,如下所示:
public void Get<T>(T? id)
where T: struct
{
Console.Write("is nullable struct");
}
Run Code Online (Sandbox Code Playgroud)
这将是捕获可为空结构的另一种重载。
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |