我经常遇到需要使用相同变量但转换为不同类型的情况。
例如:
string port;
...
ValidatePort(int port);
在 ValidatePort 中,我需要使用相同的变量 port 但它的类型应该是整数。为此,我首先需要将原始 port 转换为 int 并使用一个临时变量,如 iPort 或类似的东西将其传递给验证端口
这不是命名冲突的唯一情况,在其他所有情况下我都使用了不同的方法(如果我需要一个字符串,我将其命名为 variableName + String 或其他一些结尾)
C# 中是否有相应的命名约定或命名相似但类型不同的变量的通用方法?
请您参考如下方法:
我会说通过查看变量来明确变量是什么是明智的。
var time;
你不知道那代表什么。它可以是以下任何一个:
int time; // number of seconds
DateTime time;
TimeSpan time;
我会说
int port = 7;
string portAsString = port.toString();
但是对于上面的代码,只要调用它端口就没有问题,因为这段代码是完全有效的:
string port = "7";
int portAsInteger = int.parse(port); // If you need a temporary variable
myMethod(int.parse(port)); // You can use variable 'port' twice as scope is different
myMethod(portAsInteger);
public void myMethod(int port) { .... }
