【发布时间】:2009-05-13 12:03:31
【问题描述】:
在 C# 中,当我想从该类的另一个静态方法调用该类的静态方法时,是否可以使用 通用前缀,例如 PHP 的 self::,而不是类名字?
所以在下面的例子中,不是说 Customer.DatabaseConnectionExists(),我怎么能说像 Self.DatabaseConnectionExists() 这样的话,例如以后如果我更改类的名称,我不必更改所有前缀?
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static Customer GetCurrentCustomer()
{
if (Customer.DatabaseConnectionExists())
{
return new Customer { FirstName = "Jim", LastName = "Smith" };
}
else
{
throw new Exception("Database connection does not exist.");
}
}
public static bool DatabaseConnectionExists()
{
return true;
}
}
【问题讨论】:
-
我什么都不知道,但是你为什么不直接通过上下文菜单去“重构”——它同样可以让你免于手动编辑的麻烦
-
对,但至少从我阅读 PHP 代码的经验来看,如果你看到“self::”,你就知道你引用了那个类,不管它叫什么,如果你看到“Customer::”你必须环顾四周,看看您是否确实在 Customer 类中。它只是让代码更明确一点,这是我以前经常看到的。