方法上的 long 数据类型接受 int
long data type on method accepts an int
考虑这段代码:
static void Main()
{
int input = 10;
Console.WriteLine(GetResult(input));
}
static string GetResult(long input)
{
return (input).ToString();
}
static string GetResult(int input)
{
return (input).ToString();
}
就目前而言,Main()
方法中的代码将调用第二个 GetResult()
,它接受一个 int
参数。如果我删除第二种方法,它会自动使用第一种方法,它接受一个 long
参数。
虽然我可以理解 int
作为 Int32
适合 long
作为 Int64
,但我无法找到解释(以协助我的好奇心)关于它是如何在引擎盖下工作的。
我是应该接受它确实有效还是有人可以提供更多详细信息?
为此,需要阅读关于方法重载如何在该语言中工作的规范。当有更具体的签名匹配方法可用时,它将被调用。在上面的例子中,Int
可以隐式地是 converted/upcast 到 long
,如果没有重载采用 int
它将通过调用另一个采用 [= 的重载来结束12=] 作为输入。
例如:
int a = 1;
long b = a; // compiles due to implicit conversion
另请参阅以下文档 link 以查找 C# 中类型之间的隐式转换 post 由 @Fildor 评论:
以下 post 应该有助于理解重载解析在 C# 中的工作原理
https://csharpindepth.com/articles/Overloading
希望对您有所帮助。
考虑这段代码:
static void Main()
{
int input = 10;
Console.WriteLine(GetResult(input));
}
static string GetResult(long input)
{
return (input).ToString();
}
static string GetResult(int input)
{
return (input).ToString();
}
就目前而言,Main()
方法中的代码将调用第二个 GetResult()
,它接受一个 int
参数。如果我删除第二种方法,它会自动使用第一种方法,它接受一个 long
参数。
虽然我可以理解 int
作为 Int32
适合 long
作为 Int64
,但我无法找到解释(以协助我的好奇心)关于它是如何在引擎盖下工作的。
我是应该接受它确实有效还是有人可以提供更多详细信息?
为此,需要阅读关于方法重载如何在该语言中工作的规范。当有更具体的签名匹配方法可用时,它将被调用。在上面的例子中,Int
可以隐式地是 converted/upcast 到 long
,如果没有重载采用 int
它将通过调用另一个采用 [= 的重载来结束12=] 作为输入。
例如:
int a = 1;
long b = a; // compiles due to implicit conversion
另请参阅以下文档 link 以查找 C# 中类型之间的隐式转换 post 由 @Fildor 评论:
以下 post 应该有助于理解重载解析在 C# 中的工作原理
https://csharpindepth.com/articles/Overloading
希望对您有所帮助。