类创建和类调用方法可以解释一下 [英] Class create and class calling method can you explain me

查看:72
本文介绍了类创建和类调用方法可以解释一下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚C#中的类创建以及如何调用该类方法。请问谁可以帮助我..?



我的尝试:



如何创建一个类以及如何调用它??

Im not clear class creation in C# and how to calling that class method. please who may help me ..?

What I have tried:

How to create a class and how call that..?

推荐答案

看看。由Charles Petzold撰​​写的.NET Book Zero [ ^ ]。


假设我们有一个班级:

Assuming we have a class:
public class MyClass
   {
   public int Value;
   public int Double(int addOn) { return (Value + addOn) * 2; }
   public static int Treble (int value) {return value * 3; }
   }

然后有两种方法可以从中调用方法。

第一种方法是使用静态方法:

Then there are two ways to call a method from it.
The first is to use the static method:

int times3 = MyClass.Treble(666);

这不需要创建类的实例,但意味着静态方法无法访问或使用类的任何非静态属性,字段或方法。在这种情况下,Treble无法调用Double,或访问Value字段。一般来说,您不会使用很多静态方法。如果你想到一辆车,一个静态的问题就是车轮数量多少?因为一辆车总是有四个轮子。



另一个是使用该类的实例来访问该方法:

This doesn't require an instance of the class to be created, but means that the static method cannot access or use any non-static properties, fields, or methods of the class. In this case, Treble cannot call Double, or access the Value field. Generally speaking, you won't use many static methods. If you think of a car, a static question would be "how many wheels?" because a car always has four wheels.

The other is to use an instance of the class to access the method:

MyClass mc1 = new MyClass();
mc1.Value = 666;
MyClass mc2 = new MyClass();
mc2.Value = 333;
...
int times2 = mc1.Double(0);    // returns (666 + 0) * 2 : 1332
int times22 = mc2.Double(100); // returns (333 + 100) * 2 : 866

这次,因为Double不是静态方法,它可以访问类实例的字段 - 因此它可以根据您使用的类实例返回不同的值。

在汽车方面,这相当于问这是什么颜色的?我的车回到红色,你的车可能会返回蓝色。

This time, because Double is not a static method, it can access the fields of the class instance - so it can return different values depending on which class instance you are using.
In car terms, this is the equivalent of asking "What colour is it?" My car woudl return "red", your car might return "blue".


这篇关于类创建和类调用方法可以解释一下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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