【C#】关于Method方法的学习理解(上)

Method

简介 方法是默认是
私有
非静态的
必须有返回值,没返回值 返回 0
default private
non-static

Every method has a return type if dont have return void
**
– An encapsulated series of statements that carry out a task
– Any class can contain an unlimited number of methods
– So far you have written only a Main() method and no
others
– You have created many programs that call WriteLine()
and ReadLine() methods
– These methods are prewritten and you had only to call
them to have them do something
– When using arrays, you saw BinarySearch(), Sort() and
Reverse() methods
– These methods are prewritten; you only had to call them
to do a task for you

方法

执行任务的一系列封装语句
-任何类都可以包含无限数量的方法
-到目前为止,你只写了一个Main()方法
-你已经创建了很多调用WriteLine()的程序和ReadLine()方法
-这些方法是预先编写的,你只需要调用
让他们做点什么
-当使用数组时,您看到了BinarySearch(), Sort()和
Reverse() methods
-这些方法是预先编写的;你只需要调用他们
帮你完成一项任务

Every method has a name; the method name must be a
legal C# identifier
• Many programmers start method names with a verb because
methods cause actions

  • DeductTax(),
  • DisplayNetPay()

每个方法都有一个名称;方法名必须是
合法的c#标识符
许多程序员以动词because作为方法名的开头
方法导致
——DeductTax (),
DisplayNetPay ()


在这里插入图片描述
Parameter to a method
It is a variable that holds data passed to a method when it is
called
• The parentheses that follow a method name in its header can hold no
parameter, one parameter or multiple parameters separated with commas
– The contents within the parentheses are known as the
parameter list

– The terms argument and parameter are closely related
– An argument is the actual data in a method call
– A parameter is in the method header
参数设置为方法
-它是一个变量,保存传递给方法的数据

•方法头中的方法名后面的圆括号可以包含no
参数,一个参数或多个参数,以逗号分隔
—括号内的内容称为参数列表
—术语argument和parameter是密切相关的
参数是方法调用中的实际数据
—参数在方法头中


Choose True or False
• 1. A method header must contain declared accessibility False
方法头必须包含声明的可访问性
In many programming languages (like Java or C#), if no accessibility modifier (such as public, private, protected) is specified, a default accessibility is used (often package-private in Java or internal in C#).
在许多编程语言(如Java或c#)中,如果没有指定可访问性修饰符(如public、private、protected),则使用默认的可访问性(在Java中通常是package-private,在c#中通常是internal)。
tip:
private:私有访问修饰符,表示只有声明该成员的类内部可以访问该成员。换句话说,私有成员对于类的外部以及任何子类都是不可见的,其他类无法直接访问。这是访问级别中最封闭的一种。
internal:内部访问修饰符,表示只有声明该成员的同一程序集(Assembly)内部的类可以访问该成员。程序集是指在编译时生成的一个或多个相关的代码模块集合。内部成员对于程序集外部的类是不可见的,但程序集内部的所有类都可以访问

• 2. A method header must contain a return type False
方法必须包含返回类型
In most programming languages, every method needs to declare a return type. In languages like Java, C#, and C++, this is mandatory. Even if the method does not return any value, the return type is specified as void.
在大多数编程语言中,每个方法都需要声明一个返回类型。在Java、c#和c++等语言中,这是强制性的。即使该方法不返回任何值,返回类型也被指定为void。

• 3. A method header must contain an identifier True
方法头必须包含标识符
The method header must include the method’s name (identifier) to uniquely identify it within its scope.
方法头必须包含方法的名称(标识符),以便在其作用域中唯一地标识它。


> Implementation Hiding
实现隐藏

**
在这里插入图片描述

1.Main() Method:
The Main() method is the entry point of a C# console application. It is the method that gets called first when the program starts executing.
In your context, Main() is described as the “calling method” because it is responsible for invoking (or calling) another method.
Main()方法:
Main()方法是c#控制台应用程序的入口点。它是程序开始执行时首先调用的方法
在您的上下文中,Main()被描述为“调用方法”,因为它负责调用(或调用)另一个方法。

2.WriteLine()方法:
**WriteLine()**是系统提供的一个方法。c#中的控制台类。它用于将一行文本打印到控制台
在您的上下文中,WriteLine()是“被调用的方法”,因为它被Main()方法调用(或调用)。

using System;  
  
class HelloClass  
{  
    static void Main()  
    {  
        // Main method is the calling method  
        Console.WriteLine("Hello, World!");  // WriteLine is the called method  
    }  
}

> Understanding Methods and Implementation Hiding
理解方法和实现隐藏

Implementation Hiding1

• Major reasons to create a method:
– The code will remain short and easy to follow
– A method is easily reusable – you can use the method in
any program. Can allow other programs to use it. The same
method can be used many times.
– The WriteLine() method provides an example of implementation hiding.

• Code bloat
– Unnecessarily long or repetitive statements, repeating the
same code at several points in a program

•创建方法的主要原因:
-代码将保持简短和易于遵循
-一个方法很容易重用-你可以在任何程序,
可以允许其他程序使用它。相同的方法可多次使用。
—WriteLine()方法提供了一个示例实现隐藏。

•代码膨胀
-不必要的冗长或重复的陈述,重复
在程序的几个点上使用相同的代码

Implementation hiding2

– An important principle of object-oriented programming
– Keeps the details of a method’s operations hidden
– Examples: WriteLine() and ReadLine(). These methods
take care of all the hardware details required to produce
output or allow input
• The only concern is the way you interface, or interact, with the
method
– The program does not need to know how the method works
– Methods exist in a black box – a virtual device you can use
without knowing how it works internally
面向对象编程的一个重要原则:
隐藏方法操作的详细信息
示例:WriteLine()、ReadLine()。
这些方法注意所需的所有硬件细节输出或允许输入

唯一关心的是你与方法交互的方式
-程序不需要知道方法是如何工作的
—方法存在于一个黑匣子中->一个可以使用的虚拟设备
但是我们不知道它是如何运作的


Choose True or False (PRACTICE)
• 1. A method is an encapsulated series of statements that carry out a task
方法是执行任务的一系列封装语句 TRUE

• 2. Any class can contain an unlimited number of methods
任何类都可以包含无限数量的方法 TRUE

• 3. All the methods that will be used by your programs have been written
for you and stored in files. FALSE
你的程序将要用到的所有方法都已经写好了为您和存储在文件中。
WHY FALSE?
Not all the methods that will be used by your programs have been written for you and stored in files. You often need to write your own methods to perform specific tasks that are not covered by pre-existing libraries or frameworks.
并不是所有程序将要使用的方法都是为您编写并存储在文件中的。您经常需要编写自己的方法来执行现有库或框架未涵盖的特定任务。


A method must include:
– A method declaration, which is also called a method
header or method definition
Opening curly brace {
– A method body, which is a block of statements that carry out the
method’s work
Closing curly brace }
一个方法必须包括:

-方法声明,也称为方法
头文件或方法定义

-左花括号{
方法体,它是执行方法的语句块
-右花括号}


The Method declaration defines the rules for using the method and it contains:

– Optional declared accessibility
this specifies the level of access that other classes have to the method. Examples include public, protected, private, and package-private (no specified access modifier).
– Optional static modifier
If the method is declared as static, it belongs to the class itself and can be called without creating an instance of the class.
– Return type for the method
This specifies the data type of the value that the method returns. If the method does not return a value, the return type is void.
– Method name, or identifier
This is the unique name of the method within the class.
– Opening parenthesis
This marks the beginning of the method’s parameter list.
– Optional list of method parameters separated with
commas

These are the variables that the method requires as input. Each parameter includes a data type and a variable name.
– Closing parenthesis
This marks the end of the method’s parameter list

Method声明定义了使用该方法的规则 它包含:

-可选声明的可访问性
这指定了其他类对该方法的访问级别。示例包括public、protected、private和package-private(没有指定的访问修饰符)。
-可选静态修饰符
如果方法声明为静态,则它属于类本身,无需创建类的实例即可调用。
-方法的返回类型
这指定方法返回的值的数据类型。如果该方法不返回值,则返回类型为空
-方法名称或标识符
这是类中方法的唯一名称。
-左括号
他标志着方法参数表的开始。
-可选方法参数列表,
这些是该方法需要作为输入的变量。每个参数包括一个数据类型和一个变量名。
-右括号
这标志着方法参数列表的结束


在这里插入图片描述

**

(一)Access modifier(Public or Private)

**(一)访问修饰符(Public或Private)

• Optional declared accessibility:
• Limits how other methods can use your method

• Possible access values:

– Public access:
– established by including a public modifier in the declaration
– allows access to the method from other classes
– Private Access
– established by including a private modifier or by omitting accessibility
modifier
– This modifier limits method access only to the class that contains the
method

•可选声明的可访问性:
•限制其他方法如何使用您的方法

•可能的情况:(白话就是共有私有 public 和 private)

公共访问
-通过在声明中包括公共修饰符来建立允许从其他类访问该方法

私有访问
-通过包含私有修饰符或省略可访问性来建立修饰符
-此修饰符将方法访问限制为仅对包含方法

If you do not provide an accessibility modifier for a method
It is private by default
– Main method() headers you have used have no access
modifier; so they are private
• When you use a method’s complete name, including its class,
you are using its fully qualified name
– e.g. System.Console.WriteLine()

  • When you include
    using static System.
    Console
    at the top of your program, you do not need to use fully
    qualified method name

    如果未为方法提供可访问性修饰符
    默认为私有

    -你使用的主方法()头没有访问权限
    修饰符;所以它们是私有的
    •当你使用方法的完整名称时,包括它的类,
    您正在使用它的完全限定名
    -例如System.Console.WriteLine()
    -就是上边加了导包类似那种using static System,而且在程序顶部,不需要充分使用限定方法名称。

**

(二)An Introduction to the Optional static Modifier

You can declare a method to be static or nonstatic
– Methods are nonstatic by default
• static method
– Can be called without referring to an object
– Instead, you refer to the class
– For example, if MethodS() is static and MethodN is non static, the
following describe typical method calls:
– someClass.MethodS(); (here MethodS is static)
– SomeObject.MethodN(); (here MethodN is nonstatic)

—方法默认是非静态的
可以将方法声明为静态或非静态
•静态方法
-可以在不引用对象的情况下调用
-相反,可以用类调用
—例如,如果MethodS()是静态的,MethodN是非静态的,则
下面描述了典型的方法调用:
——someClass.MethodS ();(这里MethodS是静态的,所以可以用类调用可以看到是someClass调用的而不是Object)
——SomeObject.MethodN ();(这里MethodN是非静态的)

nonstatic method
– It is the default
– Can be used only in conjunction with an object
– Nonstatic methods can call static ones
– e.g.someObject.MethodN();
– Here, MethodN() is nonstatic
非静态的方法
—为默认值
-只能与一个对象结合使用
—非静态方法可以调用静态方法
——e.g.someObject.MethodN ();
在这里,**MethodN()**是非静态的


在这里插入图片描述
Every method has a return type
– Indicates what kind of value the method will return to any other
method that calls it
– If a method does not return a value, its return type is void
– A method’s return type is known more succinctly as a method’s
type
– You can create methods with return types such as int or double that
return values of the corresponding types.
Such methods are called value-returning methods

每个方法都有一个返回类型
-指示该方法将返回给其他方法的值
方法调用它
—如果方法没返回值,则其返回类型为void
-方法的返回类型更简洁地称为方法
类型
-您可以创建返回类型为int或double that的方法
返回相应类型的值。
这样的方法称为返回值方法


1.Understand methods and implementation hiding
理解方法和实现隐藏
2.Write methods with no parameters and no return value
编写不带参数和返回值的方法

using System;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        PrintGreeting();  
    }  
  
    static void PrintGreeting()  
    {  
        Console.WriteLine("Hello, World!");  
    }  
}

3.Write methods that require a single argument
编写只需要一个参数的方法

using System;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        PrintMessage("Welcome to C#");  
    }  
  
    static void PrintMessage(string message)  
    {  
        Console.WriteLine(message);  
    }  
}

4.编写需要多个参数的方法
Write methods that require multiple parameters

using System;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        AddNumbers(5, 10);  
    }  
  
    static void AddNumbers(int num1, int num2)  
    {  
        int sum = num1 + num2;  
        Console.WriteLine($"Sum: {sum}");  
    }  
}

5.Write Methods that Return a Value
编写返回值的方法

using System;  
class Program  
{  
    static void Main(string[] args)  
    {  
        int sum = AddNumbers(5, 10);  
        Console.WriteLine($"Sum: {sum}");  
    }  
  
    static int AddNumbers(int num1, int num2)  
    {  
        return num1 + num2;  
    }  
}

6.Implementation Hiding实现隐藏

Implementation hiding is about encapsulating the internal workings of a class from the outside world. This is often achieved using access modifiers like private, protected, and internal.

Here’s an example that demonstrates implementation hiding by using private fields and a public method:
In this example, the Calculator class hides the implementation details of how numbers are stored and added by using private fields _number1 and _number2. The SetNumbers and Add methods expose a public interface for interacting with the calculator, without revealing the internal state directly.

By following these examples, you should be able to write methods in C# that adhere to different parameter and return type requirements, as well as understand the basics of implementation hiding.

实现隐藏是关于从外部世界封装类的内部工作。这通常是通过private、protected和internal等访问修饰符实现的。

下面是一个示例,演示了通过使用私有字段和公共方法实现隐藏:
在本例中,Calculator类隐藏了如何使用私有字段_number1和_number2存储和添加数字的实现细节。SetNumbers和Add方法公开了一个与计算器交互的公共接口,而不直接显示内部状态。

通过遵循这些示例,您应该能够在c#中编写遵循不同参数和返回类型要求的方法,并了解实现隐藏的基础知识。

using System;  
  
class Calculator  
{  
    // Private fields  
    private int _number1;  
    private int _number2;  
  
    // Public method to set values for private fields  
    public void SetNumbers(int number1, int number2)  
    {  
        _number1 = number1;  
        _number2 = number2;  
    }  
  
    // Public method to add the private fields  
    public int Add()  
    {  
        return _number1 + _number2;  
    }  
}  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        Calculator calc = new Calculator();  
        calc.SetNumbers(5, 10);  
        int result = calc.Add();  
        Console.WriteLine($"Result: {result}");  
    }  
}

**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值