![](/img/trans.png)
[英]What is the equivalent function of PHP's number_format in C#?
[英]What is the C# equivalent to PHP's “self::”?
在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;
}
}
沒有真正的等價物 - 你必須指定類名,即
Customer.DatabaseConnectionExists()
或完全錯過預選賽,即
DatabaseConnectionExists()
后一種調用方式是可取的,因為它更簡單並且不會失去任何意義。 此外,它更多內聯方法調用實例(即由InstanceMethod()
調用,而不是 this.InstanceMethod()
,這是過於冗長)。
如果你從類中調用方法,你不需要像:: Self那樣指定任何東西,只需要方法名稱即可。
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static Customer GetCurrentCustomer()
{
if (DatabaseConnectionExists())
{
return new Customer { FirstName = "Jim", LastName = "Smith" };
}
else
{
throw new Exception("Database connection does not exist.");
}
}
public static bool DatabaseConnectionExists()
{
return true;
}
}
把它留下來吧。 DatabaseConnectionExists
在類中定義。
只需調用它,不帶任何前綴。
不,沒有。 但是使用重構工具,更改類的名稱不應該太擔心你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.