如何命名相同的变量,但名称不同

时间:2011-10-05 09:46:48

标签: c# variables naming-conventions

当我需要使用相同的变量但转换为不同的类型时,我经常遇到这种情况。

例如:

string port;
...
ValidatePort(int port);

这里ValidatePort我需要使用相同的变量port但它的类型应该是整数。为此,我首先需要将原始port转换为int并使用iPort之类的临时变量或类似内容将其传递给ValidatePort

这不是命名冲突的唯一情况,在其他任何情况下我都使用不同的方法(如果我需要一个字符串,我称之为variableName + String或其他一些结尾)

C#中是否存在命名约定或命名变量相似但不同类型的常用方法?

5 个答案:

答案 0 :(得分:2)

我想说通过查看变量是明智的做法是明智的。

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) { .... }

答案 1 :(得分:2)

我真的没有看到问题 - 为什么你不能这样称呼它:

ValidatePort(int.Parse(port));

那就是说,我不喜欢这样的代码 - 它本质上使用“stringly typing”,这是一件坏事。您需要使用类型前缀来消除名称歧义这一事实清楚地表明您做错了。

那就是:如果Port变量确实是一个数字,那么它首先应该永远不应该是String类型。尽快使用正确的类型。

例如,如果您通过TextBox从用户那里获得端口号,则不要将内容存储为字符串,请立即使用正确的类型:

int port;
if (! int.TryParse(portInput.Text, out port)) {
    // Handle wrong user input.
}

(注意错误处理对所有用户输入都很重要。)

答案 2 :(得分:0)

您可以使用许多符号:

strSomething
somethingStr
szSomething // Microsoft uses this in their C stuff

这是一个偏好问题。最佳做法是拥有描述性变量,并以任何最适合特定情况的方式处理碰撞。只是不要在任何地方切换样式,这样最终会让人感到困惑。

答案 3 :(得分:0)

您可以为类范围字段使用前缀:

string _port;
object _anyObject;
bool _anyBool;
public bool AnyBool {get{return _anyBool;}}
void Validate(int port)
{
    /..
}

答案 4 :(得分:0)

当前版本的C#不支持此功能(另外,我认为未来版本不支持此功能)。您可以在整个项目中定义自己的标准,以避免这种命名冲突。只是一个疯狂的猜测 - 当你想要同名但不同的类型时,它是否意味着两者的价值来源不同。例如,从文本框中读取时,值可能是字符串,而您使用的是string port,但对于实际操作,它要求它为integerint port)。如果是这种情况,那么您可以使用一些前缀来指示此值所属的位置。

相关问题