简体   繁体   English

C# 命名空间只能访问使用 static 关键字声明的方法吗?

[英]C# Can namespaces only access methods which are declared with the static keyword?

I'm new to C#.我是 C# 的新手。 The question i had was regarding namespaces.我的问题是关于命名空间。 This is what i have.这就是我所拥有的。

namespace A {命名空间 A {

namespace B {

   public class Family {

        public static void Print() {   

            Console.WriteLine("HIIIIIIIII");
        
        }

    }

}

} }

Now I can access the method "Print" in the main using ---------------ABFamily.Print();-------------------现在我可以使用 ---------------ABFamily.Print();---------------- 在 main 中访问方法“Print” ---

But I cannot access the Print method if i remove the static keyword in the declaration.但是,如果删除声明中的 static 关键字,则无法访问 Print 方法。 Is it because you can only access static methods inside a namespace?是因为您只能访问命名空间内的静态方法吗?

Thanks in advance提前致谢

Static methods can be called the way you showed.静态方法可以按照您展示的方式调用。 Non static methods (also called instance methods) need an object instance so that you call.非静态方法(也称为实例方法)需要一个对象实例以便您调用。

So in order to call your methods after you remove static keyword from your method you need to create an object instance.因此,为了在从方法中删除static关键字后调用您的方法,您需要创建一个对象实例。

For example:例如:

var myFamily = new A.B.Family();
myFamily.Print();

For more info refer to C# Documentation有关更多信息,请参阅C# 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 static 方法中的 public 关键字从 C# 中的另一个 class 访问它 - Using the public keyword in static methods to access it from another class in C# 局部类可以在C#中访问静态方法吗? - Can partial class access static methods in C#? 为什么C#不允许在方法中将变量声明为静态? - Why does C# not allow variables to be declared static in methods? 在C#中静态方法的形式参数中使用“ this”关键字 - Use of “this” keyword in formal parameters for static methods in C# 扩展方法中的C#静态类访问 - c# static class access in extension methods 为什么我们不能在 C# 中使用访问修饰符和 static 关键字来创建对象? - Why can't we use access modifiers and static keyword for creating an object in C#? 你能在声明为void的C#方法中使用“return”语句吗? - Can you use the “return” statement in C# methods declared as void? 如何访问在单独的类中声明的ENUM - C# - How to access ENUM which is declared in a separate class - C# 可以在 C# 中的密封类中声明密封类或静态类吗? - Can a sealed or static class be declared inside a sealed class in C#? 您是否可以要求在C#中以正确的顺序声明静态函数? - Can you require static functions to be declared in the right order in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM