简体   繁体   English

名称空间中的ASP.net C#公共可访问函数

[英]ASP.net c# publicly accessible functions in namespace

In my namespace I can have public classes which are accessible to all other pages in my namespace. 在我的命名空间中,我可以拥有公共类,该公共类可供我的命名空间中的所有其他页面访问。 How do I go about having public functions? 我该如何发挥公共职能? Do I have to create a class with the functions in it? 我必须创建一个包含函数的类吗? Or is there an easier way? 还是有更简单的方法?

In C#, all functions (which are actually called methods in C# terminology) are to be declared in a type (a class or a struct). 在C#中,所有函数(实际上在C#术语中称为方法 )都将以类型 (类或结构)声明。

However, there is the concept of static classes in C#, which are good for the purpose of replacing “global functions” in older programming languages: 但是,C#中存在静态类的概念,它对于替换较旧的编程语言中的“全局函数”非常有用:

public static class MyUtilityFunctions
{
    public static void PrintHello()
    {
        Console.WriteLine("Hello World!");
    }
}

Now you can, anywhere in your program, write: 现在,您可以在程序中的任何位置编写:

MyUtilityFunctions.PrintHello();

A static method is a method that doesn't require an object. 静态方法是不需要对象的方法。 A static class is a class that contains only static methods (and static fields, static properties etc.). 静态类是仅包含静态方法(以及静态字段,静态属性等)的类。

Functions (Methods) "live" in types, so you need to put them in classes or structs. 函数(方法)在类型中是“活动的”,因此您需要将它们放在类或结构中。 By default they would be private so you need to specify the public access modifier for them to be accessible: 默认情况下,它们将是私有的,因此您需要指定public访问修饰符以使其可访问:

namespace myNameSpace
{
  public class myClass
  {
    public void MyMethod()
    {
    }
  }
}

See MSDN - Methods section of the C# programming guide. 请参阅C#编程指南的“ MSDN- 方法”部分。

When doing C#, functions can only live in types (classes and structures). 使用C#时,函数只能存在于类型(类和结构)中。 You can not declare a function on its own. 您不能单独声明一个函数。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM