非静态类中的静态方法和静态类中的静态方法有什么区别? [英] What is the difference between static methods in a Non static class and static methods in a static class?

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

问题描述

我有两个类 Class A 和 ClassB:

I have two classes Class A and ClassB:

static class ClassA
{
    static string SomeMethod()
    {
        return "I am a Static Method";
    }
}

class ClassB
{
    static string SomeMethod()
    {
        return "I am a Static Method";
    }
}

我想知道ClassA.SomeMethod();ClassB.SomeMethod();

当它们都可以在不创建类的实例的情况下访问时,为什么我们需要创建一个静态类而不是只使用非静态类并将方法声明为静态?

When they both can be accessed without creating an instance of the class, why do we need to create a static class instead of just using a non static class and declaring the methods as static?

推荐答案

唯一区别在于非静态类中的静态方法不能扩展方法.

The only difference is that static methods in a nonstatic class cannot be extension methods.

换句话说,这是无效的:

In other words, this is invalid:

class Test
{
    static void getCount(this ICollection<int> collection)
    { return collection.Count; }
}

而这是有效的:

static class Test
{
    static void getCount(this ICollection<int> collection)
    { return collection.Count; }
}

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

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