C# 创建和使用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10175357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:45:31  来源:igfitidea点击:

C# Creating and using Functions

c#function

提问by CaTx

I need help with C# programming; I am new to it and I come from C background. I have a Console Application like this:

我需要 C# 编程方面的帮助;我是新手,我来自 C 背景。我有一个这样的控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Add_Function
{
   class Program
   {
      static void Main(string[] args)
      {
         int a;
         int b;
         int c;

         Console.WriteLine("Enter value of 'a':");
         a = Convert.ToInt32(Console.ReadLine());

         Console.WriteLine("Enter value of 'b':");
         b = Convert.ToInt32(Console.ReadLine());

         //why can't I not use it this way?
         c = Add(a, b);
         Console.WriteLine("a + b = {0}", c);
      }//END   Main

      public int Add(int x, int y)
      { 
         int result = x + y;
         return result;
      }//END   Add
   }//END      Program
}//END         Add_Function

It gives me this error on the line that I call Add():

它在我调用 Add() 的行上给了我这个错误:

An object reference is required for the non-static field, method, or property 'Add_Function.Program.Add(int, int)'

非静态字段、方法或属性“Add_Function.Program.Add(int, int)”需要对象引用

Can anyone please explain to me why I have this problem. Is this because the architecture of C# is different than C, and the way I call it is wrong? Thanks.

任何人都可以向我解释为什么我有这个问题。是不是因为C#的架构和C不一样,我调用的方式不对?谢谢。

采纳答案by ean5533

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

注意:在 C# 中,术语“函数”经常被术语“方法”代替。对于这个问题,没有区别,所以我只使用术语“函数”。

The other answers have already given you a quick way to fixyour problem (just make Adda staticfunction), but I'd like to explain why.

其他答案已经为您提供了解决问题的快速方法(只需创建Add一个static函数),但我想解释一下原因。

C# has a fundamentally different design paradigm than C. That paradigm is called object-oriented programming(OOP). Explaining all the differences between OOP and functional programming is beyond the scope of this question, but here's the short version as it applies to you.

C# 具有与 C 根本不同的设计范式。这种范式称为面向对象编程(OOP)。解释 OOP 和函数式编程之间的所有差异超出了这个问题的范围,但这是适用于您的简短版本。

Writing your program in C, you would have created a function that adds two numbers, and that function would exist independently and be callable from anywhere. In C# most functions don't exist independently; instead, they exist in the context of an object. In your example code, only an instance (an object) of the class Programknows how to perform Add. Said another way, you have to create an instance of Program, and then ask Programto perform an Addfor you.

用 C 编写程序,您将创建一个将两个数字相加的函数,该函数将独立存在并可从任何地方调用。在 C# 中,大多数函数不是独立存在的;相反,它们存在于对象的上下文中。在您的示例代码中,只有该类的一个实例(一个对象)Program知道如何执行Add. 换句话说,您必须创建一个 实例Program,然后要求为您Program执行一个Add

The solutions that people gave you, using the statickeyword, route around that design. Using the statickeyword is kind of like saying, "Hey, this function I'm defining doesn't need any context/state, it can just be called." Since your Addfunction is very simple, this makes sense. As you start diving deeper into OOP, you're going to find that your functions get more complicated and rely on knowing their state/context.

人们使用static关键字为您提供的解决方案围绕该设计进行。使用static关键字有点像说,“嘿,我定义的这个函数不需要任何上下文/状态,它可以被调用。” 由于您的Add功能非常简单,这是有道理的。当您开始深入研究 OOP 时,您会发现您的函数变得更加复杂并且依赖于了解它们的状态/上下文。

My advice: Pick up an OOP book and get ready to switch your brain from functional programming to OOP programming. You're in for a ride.

我的建议:拿起一本面向对象编程的书,准备好将你的大脑从函数式编程转向面向对象编程。你是来兜风的。

回答by Daniel A. White

What that build error is telling you, that you have to either have an instance of Programor make Addstatic.

构建错误告诉您的是,您必须拥有一个实例Program或使其成为Add静态。

回答by dasblinkenlight

This code gives you an error because your Addfunction needs to be static:

这段代码给你一个错误,因为你的Add函数需要static

static public int Add(int x, int y)

In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions andstatic functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.

在 C# 中,操作实例的函数(非静态)和不操作实例的函数(静态)是有区别的。实例函数可以调用其他实例函数静态函数,因为它们具有对实例的隐式引用。相反,静态函数只能调用静态函数,否则它们必须显式提供一个实例来调用非静态函数。

Since public static void Main(string[] args)is static, all functions that it calls need to be static as well.

由于public static void Main(string[] args)是静态的,它调用的所有函数也必须是静态的。

回答by Tony The Lion

You should either make your Addfunction staticlike so:

你应该让你的Add功能static像这样:

static public int Add(int x, int y)
{ 
    int result = x + y;
    return result;
 } //END   Add

staticmeans that the function is not class instance dependent. So you can call it without needing to create a class instance of Programclass.

static意味着该函数不依赖于类实例。所以你可以在不需要创建类的类实例的情况下调用它Program

or you should create in instance of your Programclass, and then call Addon this instance. Like so:

或者你应该在你的Program类的实例中创建,然后调用Add这个实例。像这样:

Program prog = new Program();
prog.Add(5,10);

回答by Bali C

Just make your Addfunction staticby adding the statickeyword like this:

只需通过添加这样的关键字来制作您的Add功能:staticstatic

public static int Add(int x, int y)

回答by Hussein Zawawi

Because your function is an instance or non-static function you should create an object first.

因为您的函数是一个实例或非静态函数,所以您应该先创建一个对象。

Program p=new Program();
p.Add(1,1)

回答by ANXIOUS117

The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y);or you could just copy and paste your entire Addfunction above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D

您出现错误的原因是因为您的 add 函数是在 main 中使用它之后定义的,如果您要在 main 之前创建一个函数原型,public int Add(int x, int y);或者您可以将整个Add函数复制并粘贴到 main 之上, main 是哪里编译器开始执行,所以在你使用它之前声明和定义一个函数没有意义,希望有帮助。:D

回答by trinalbadger587

you have to make you're function static like this

你必须让你的功能像这样静态

namespace Add_Function
{
  class Program
  {
    public static void(string[] args)
    {
       int a;
       int b;
       int c;

       Console.WriteLine("Enter value of 'a':");
       a = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Enter value of 'b':");
       b = Convert.ToInt32(Console.ReadLine());

       //why can't I not use it this way?
       c = Add(a, b);
       Console.WriteLine("a + b = {0}", c);
    }
    public static int Add(int x, int y)
    {
        int result = x + y;
        return result;
     }
  }
}

you can do Program.Add instead of Add you also can make a new instance of Program by going like this

你可以做 Program.Add 而不是 Add 你也可以像这样创建一个新的 Program 实例

Program programinstance = new Program();

回答by user3479886

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

注意:在 C# 中,术语“函数”经常被术语“方法”代替。对于这个问题,没有区别,所以我只使用术语 "function"

Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.

这不是真的。您可以阅读(func 类型+ Lambda 表达式)、(匿名函数“使用委托类型”)、(操作类型+Lambda 表达式)、(谓词类型+Lambda 表达式)。等等......等等......这会起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           int a;
           int b;
           int c;

           Console.WriteLine("Enter value of 'a':");
           a = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("Enter value of 'b':");
           b = Convert.ToInt32(Console.ReadLine());

           Func<int, int, int> funcAdd = (x, y) => x + y;
           c=funcAdd.Invoke(a, b);
           Console.WriteLine(Convert.ToString(c));

        }

     }
}

回答by TechNerdGamer

static void Main(string[] args)
    {
        Console.WriteLine("geef een leeftijd");
        int a = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("geef een leeftijd");
        int b = Convert.ToInt32(Console.ReadLine());

        int einde = Sum(a, b);
        Console.WriteLine(einde);
    }
    static int Sum(int x, int y)
    {
        int result = x + y;
        return result;
    }