静态类和静态方法的区别是什么 [英] What's the difference of Static Class and Static Method

查看:208
本文介绍了静态类和静态方法的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个疑问让我伤了好几个月......

我想知道差异&静态类和静态方法的用法...

例如:我有这样的课程



Hi,
This doubt is killing me for many months...
I want to know the difference & usages of Static Class and Static Methode...
FOr Eg: I have a class like this

static class ABC
{
    public int a ; 
    public void function_a()
    {
      a = 10;
    }
}





和另一个类似这样的





and another class like this

class DEF
{
    public static int a ;
    public static void function_a()
    {
       a= 10;
    }
}





我多次使用过第二种类型,,,我知道用法....

但第一类CLass的用法是什么.....请回答:(



I have used the second type of class many times,,, and I know the usage....
But what's the usage of First type of CLass ..... Please Answer :(

推荐答案

你的第一个示例将无法编译,静态类必须具有所有静态成员。



仅使用一些静态方法和静态类之间的区别在于您告诉编译器第二个例子你可以创建一个DEF类的对象,即使它没有实例方法.ABC类不能用new运算符实例化(会得到编译时错误)。
Your first example will not compile, a static class must have all static members.

The difference between just using some static methods and a static class is that you are telling the compiler that the class cannot be instantiated. The second example you can create an object of the DEF class even though there are no instance methods in it. The ABC class cannot be instantiated with the new operator (will get a compile-time error).


来自MSDN的参考



何时使用静态类

-------- -------------------------------------------------- ----------------------



假设您有一个包含以下方法的CompanyInfo类s获取有关公司名称和地址的信息。



C#

A reference from MSDN

When to Use Static Classes
--------------------------------------------------------------------------------

Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.

C#
 class CompanyInfo
{
    public string GetCompanyName() { return "CompanyName"; }
    public string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}



这些方法不需要附加到类的特定实例。因此,您可以将其声明为静态类,而不是创建此类的不必要实例,如下所示:



C#


These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:

C#

 static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}



使用静态类作为与特定对象无关的方法的组织单位。此外,静态类可以使您的实现更简单,更快,因为您不必创建对象来调用其方法。以有意义的方式组织类中的方法很有用,例如System命名空间中Math类的方法。


Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.


这篇关于静态类和静态方法的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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