简体   繁体   English

C# 方法参数有什么意义?

[英]What's the point of C# Method Parameters?

I'm new to coding, and I'm curious as to why Method Parameters are useful.我是编码新手,我很好奇为什么方法参数很有用。 What's the point to them when I can create a variable within the method which should execute when I call on it?当我可以在调用它时应该执行的方法中创建一个变量时,它们有什么意义? What's the point of giving it that parameter?给它那个参数有什么意义?

In your example, let's say you wanted to say hello to more than just Mike.在您的示例中,假设您想向不仅仅是 Mike 打招呼。 You could do this:你可以这样做:

SayHi("Mike");
SayHi("Amy");
SayHi("Sam");

Let's take it a step further.让我们更进一步。 You can create a collection of names, and say hi to any number of people您可以创建一个姓名集合,并向任意数量的人打招呼

List<string> people = new List<string> { "Mike", "Amy", "Sam", "John", "Mindy" };
foreach (string person in people) 
{
    SayHi(person);
}

As you can see, the SayHi() function is reuseable because you can call it any number of times.如您所见, SayHi()函数是可重用的,因为您可以多次调用它。

And for one more step further, let's say that later you realized that you didn't want to say "Hello " + name , you wanted to say, "Hello, " + name + ". How are you?"再进一步,假设后来你意识到你不想说"Hello " + name ,你想说, "Hello, " + name + ". How are you?" then you'd only have to change the code in one place and all the times it was used will be affected.那么你只需要在一个地方更改代码,它的所有使用时间都会受到影响。

Adding a parameter is a way to say "This piece of reusable code is only useful as long as it has this value to use".添加一个参数是一种表达“这段可重用代码只有在它有这个值可以使用时才有用”的方式。 In your sample code, the value that SayHi needs is a name because it needs to know whom to say hi to.在您的示例代码中, SayHi需要的值是一个名称,因为它需要知道向谁打招呼。

Parameters can be used for a couple different things.参数可用于几个不同的事情。 The most practical use is to avoid repetition as Phong said in their answer.最实际的用途是避免重复 Phong 在他们的回答中所说的。 For example, if I want to print a single line of red text to the console, I could do this:例如,如果我想在控制台打印一行红色文本,我可以这样做:

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This is some red text");
Console.ResetColor();

Console.WriteLine("This is some boring white text");

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("And this is some more red text!");
Console.ResetColor();

OR I could create a function with an input parameter for the text to display red like this:或者我可以创建一个带有输入参数的函数,用于文本显示红色,如下所示:

static void WriteRed(string output){
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine(output);
    Console.ResetColor();
}

WriteRed("This is some red text");
Console.WriteLine("This is some boring white text");
WriteRed("And this is some more red text!");

As you can see, we turned this task from a 3 line task, to a 1 line task, which would not be possible without input parameters.如您所见,我们将此任务从 3 行任务转变为 1 行任务,这在没有输入参数的情况下是不可能的。 This will be very useful in case we need to write in red anywhere else in the program.如果我们需要在程序的其他任何地方用红色书写,这将非常有用。

Obviously this is a pretty simple example, and in more complex programs this could easily save you 100+ lines.显然,这是一个非常简单的示例,在更复杂的程序中,这可以轻松地为您节省 100 多行代码。

Another use is for organization.另一个用途是用于组织。 Let's say you have a program that takes user input and processes it in some way.假设您有一个接受用户输入并以某种方式处理它的程序。 Using functions with input parameters, you can put the user input gathering in one .cs file, and the processing in another.使用带有输入参数的函数,您可以将用户输入收集放在一个 .cs 文件中,并将处理放在另一个文件中。

Parameters are also really useful in constructors, which if you haven't gotten to yet, are just functions that are called when a new instance of an object is created.参数在构造函数中也非常有用,如果您还没有了解,构造函数只是在创建对象的新实例时调用的函数。

What's the point of giving it that parameter?给它那个参数有什么意义?

It helps you Reuse some actions with the same steps.它可以帮助您以相同的步骤Reuse某些操作。 Don't repeat yourself不要重复自己

As you can see, You just pass the param then inside the method will help you dosomething ("Hello" + passedparameter)如您所见,您只需传递参数,然后在方法内部就会帮助您做一些事情(“Hello”+passedparameter)

You should read the fundamentals of OOP (object oriented programming).您应该阅读 OOP(面向对象编程)的基础知识。 This will help you understand basic principles like method overloading, overriding and inheritance which are commonly used.这将帮助您了解常用的方法重载、覆盖和继承等基本原则。 Instead of writing multiple single-line statements you can create functions that are structured, cleanly written code.您可以创建结构化的、编写干净的代码的函数,而不是编写多个单行语句。 Also, following different design patterns, it allows us to give functions the ability to handle single responsibilities and make everything cleaner imo!此外,遵循不同的设计模式,它允许我们赋予函数处理单一职责的能力,并使一切变得更清晰!

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/object-oriented-programming https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/object-oriented-programming

C# is Object-oriented programming language C#是面向对象的编程语言


Object-oriented programming, or OOP, is an approach to problem-solving where all computations are carried out using objects.面向对象编程(OOP)是一种解决问题的方法,其中所有计算都使用对象进行。 An object is a component of a program that knows how to perform certain actions and how to interact with other elements of the program.对象是程序的一个组件,它知道如何执行某些操作以及如何与程序的其他元素进行交互。

Once you have created objects, you want them to be able to do something.创建对象后,您希望它们能够执行某些操作。 This is where methods come in. A method in object-oriented programming is a procedure associated with a class.这就是方法的用武之地。面向对象编程中的方法是与类相关联的过程。 A method defines the behavior of the objects that are created from the class.方法定义从类创建的对象的行为。 Another way to say this is that a method is an action that an object is able to perform.另一种说法是,方法是对象能够执行的操作。 The association between method and class is called binding .方法和类之间的关联称为绑定

Consider the example of an object of the type ' person ,' created using the person class.考虑使用 person 类创建的类型为“ person ”的对象的示例。 Method s associated with this class could consist of things like walking and driving .与此类关联的方法可以包括步行和驾驶等 Methods are sometimes confused with functions, but they are distinct.方法有时与函数混淆,但它们是不同的。 A function is a combination of instructions that are combined to achieve some result.函数是指令的组合,这些指令组合在一起以实现某种结果。 A function typically requires some input (called arguments/ parameters ) and returns some results .一个函数通常需要一些输入(称为参数/参数)并返回一些结果 For example, consider the example of driving a car.例如,考虑驾驶汽车的例子。 To determine the mileage, you need to perform a calculation using the distance driven and the amount of fuel used.要确定里程,您需要使用行驶距离和使用的燃料量进行计算。 You could write a function to do this calculation.您可以编写一个函数来进行此计算。 The arguments going into the function would be distance and fuel consumption , and the result would be mileage.进入函数的参数将是distance 和 fuel消耗,结果将是 mileage 。 Anytime you want to determine the mileage , you simply call the function to perform the calculation.任何时候您想确定里程数,您只需调用该函数来执行计算。

How does this differ from a method?这与方法有何不同? A function is independent and not associated with a class.函数是独立的,与类无关。 You can use this function anywhere in your code, and you don't need to have an object to use it.您可以在代码中的任何位置使用此函数,并且不需要有对象来使用它。

What's the point to them when I can create a variable within the method which should execute when I call on it

If you create a variable inside the method you can only assign it with one value at the time of code writing, but if you pass it as a parameter you can dynamically assign whatever value you want when you call the method later, even a value you don't know at the time of code writing, this value can be assigned on the run time.如果在方法内部创建一个变量,则只能在编写代码时为其分配一个值,但是如果将其作为参数传递,则可以在稍后调用该方法时动态分配您想要的任何值,甚至是您想要的值不知道在写代码的时候,这个值可以在运行时赋值。

Also, methods are used to encapsulate some logic, let say you want a method to calculate the area of a circle which is π r2 , you know the value of the PI π because it is a constant which is almost 3.14, but you don't know the radius value r because it varies from circle to another so you need to pass it to the method as parameter.此外,方法用于封装一些逻辑,假设您想要一种计算圆面积的方法,即π r2 ,您知道 PI π的值,因为它是一个几乎为 3.14 的常数,但您不知道t 知道半径值r因为它从一个圆到另一个圆而变化,所以您需要将它作为参数传递给该方法。

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

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