什么是C#相当于PHP的"自::"? [英] What is the C# equivalent to PHP's "self::"?

查看:124
本文介绍了什么是C#相当于PHP的"自::"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#,当我想从另一个类的静态方法调用类的静态方法,有一个通用前缀,我可以使用,如PHP的自:: 而不是类名?



因此,在下面的例子中,而不是说的 客户。 DatabaseConnectionExists() ,我怎么能这样说的 Self.DatabaseConnectionExists() 所以如以后如果我改变类的名字,我没有去改变所有的前缀?



 类客户
{
公共字符串名字{获得;组; }
公共字符串名字{获得;组; }

公共静态客户GetCurrentCustomer()
{
如果(Customer.DatabaseConnectionExists())
{
返回新的客户{名字=吉姆 ,姓氏=史密斯};
}
,否则
{
抛出新的异常(数据库连接不存在。);
}
}

公共静态布尔DatabaseConnectionExists()
{
返回真;
}
}


解决方案

有没有真正的等价物 - 你必须要么指定类名,即

  Customer.DatabaseConnectionExists()

或完全错过了资格赛,即

  DatabaseConnectionExists()

主叫后者的风格是明智的,因为它更简单,并且不失去了任何意义。此外,它更内嵌方法调用的实例(即由调用InstanceMethod() this.InstanceMethod() ,这是过于详细)。


In C# when I want to call a static method of a class from another static method of that class, is there a generic prefix that I can use such as PHP's self:: instead of the class name?

So in the below example, instead of saying Customer.DatabaseConnectionExists(), how can I say something like Self.DatabaseConnectionExists() so e.g. later if I change the name of the class I don't have to go change all the prefixes?

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;
    }
}

解决方案

There's no real equivalent - you have to either specify the class name, i.e.

Customer.DatabaseConnectionExists()

or miss out the qualifier altogether, i.e.

DatabaseConnectionExists()

The latter style of calling is advisable since it's simpler and doesn't lose any meaning. Also, it's more inline with method calling in instances (i.e. calling by InstanceMethod() and not this.InstanceMethod(), which is overly verbose).

这篇关于什么是C#相当于PHP的"自::"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆