与C#相关的查询和有关类中函数的问题 [英] c# related query and problem regarding functions in classes

查看:86
本文介绍了与C#相关的查询和有关类中函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一类具有两个成员函数,那么如何通过另一个成员函数访问成员函数的数据.

例如,有两个功能:

If there is one class having two member function then how to access the data of member function by the other member function.

e.g there are two functions:

 public void accept()
   {
        Console.WriteLine("Enter the first digit");
a=Convert.ToInt32(Console.ReadLine());	
	   Console.WriteLine("Enter the second digit");
b=Convert.ToInt32(Console.ReadLine());	

   }



那么我们如何访问另一个函数的a和b的值进行计算呢?



Then how can we access the value of a and b for another function for calculation?

public void calc()
{
 c=a+b;
}

推荐答案

我想您对开发还很陌生:)
有几种方法可以实现您想要的,最简单的方法(但不一定是最好的方法,具体取决于您的工作)是:


I guess you are pretty new to development :)
there are a few ways to achieve what you want, the simplest (but not necessarily the best, depending what you are doing) is:


public void Accept()
{
  Console.WriteLine("Enter the first digit");
  int a=Convert.ToInt32(Console.ReadLine()); 
  Console.WriteLine("Enter the second digit");
  int b=Convert.ToInt32(Console.ReadLine()); 
  int answer = Calculate(a, b);
}

int Calculate(int firstValue, int secondValue)
{
  return firstValue + secondValue;
}



您当然可以在Accept方法中添加a和b,但是我想您不想这样做.如果您正在做很多这样的事情,则应该创建类似Calculator类的内容,具体的实现取决于您需要执行的操作.我强烈建议您使用Google搜索"C#属性"和对象方向".学习语言时,真正值得学习面向对象,否则您将与该语言作斗争而不是使用它.



You can of course just add a and b in the Accept method, but I assume you don''t want to do this. If you are doing a lot of this sort of stuff, you should create something like a Calculator class, the exact implementation depends on what you need to do. I strongly suggest you google for "C# Properties" and "Object Orientation". Object Orientation is really worth learning as you learn the language, otherwise you will end up fighting the language rather than working with it.


在哪里声明了a, bc?

您需要阅读有关变量作用域"的参考书,这非常重要.如果在函数calc中声明了ab,则将无法从该函数外部访问它们.如果在类声明中声明它们,则该类中的任何函数都将可以访问,但是您的函数似乎都不在类内(尽管我对C#不熟悉,所以我可能对此有误).
Where are a, b and c declared?

You need to read a reference book about the ''scope'' of a variable, it is very important. If you had declared a and b inside your function calc, you would not be able to access them from outside that function. If you declare them within the class declaration then any function in that class would be able to access then, however neither of your functions appear to be within a class (although I am not familiar with C#, so I could be wrong about that).


这篇关于与C#相关的查询和有关类中函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆