在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;
}
}
Run Code Online (Sandbox Code Playgroud)
Nol*_*rin 15
没有真正的等价物 - 你必须指定类名,即
Customer.DatabaseConnectionExists()
Run Code Online (Sandbox Code Playgroud)
或完全错过预选赛,即
DatabaseConnectionExists()
Run Code Online (Sandbox Code Playgroud)
后一种调用方式是可取的,因为它更简单并且不会失去任何意义.此外,它更多地与实例中的方法调用内联(即调用by InstanceMethod()和not this.InstanceMethod(),这是过于冗长).
Kir*_*ein 13
如果你从类中调用方法,你不需要像:: 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;
}
}
Run Code Online (Sandbox Code Playgroud)