Vam*_*msi 37 c# oop static static-methods non-static
我有两个班级A和ClassB:
static class ClassA
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
class ClassB
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道ClassA.SomeMethod();
和之间有什么区别ClassB.SomeMethod();
如果可以在不创建类实例的情况下访问它们,为什么我们需要创建静态类而不是仅使用非静态类并将方法声明为静态?
Meh*_*dad 37
该唯一的区别是,在非静态类的静态方法不能扩展方法.
换句话说,这是无效的:
class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
Run Code Online (Sandbox Code Playgroud)
这是有效的:
static class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*n S 14
静态类只能包含静态成员.
静态方法确保即使您要创建多个classB对象,它们也只会使用单个共享的SomeMethod函数.
从技术上讲,除了ClassA的SomeMethod 必须是静态的之外没有区别.