![](/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.