C#中的新类(i)是什么意思? [英] What does new Class(i) in C# mean?

查看:259
本文介绍了C#中的新类(i)是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当浏览一些关于C#对象创建的网站上的文章时,我看到一行使用代码创建一个实例

When going through an article in some website regarding C# object creation, I saw a line that creates an instance using the code

new Class(i);





其中'i'已定义。



使用上面的类构造函数意味着什么?这是可能的方式还是错的?这将如何工作?在这里创建了哪个类的对象?任何人都可以帮我理解一下吗?在此先感谢



Where 'i' is already defined.

What does it mean of using a class constructor like above? Is that a possible way or is it wrong ? How this will work? Which class's object is created here? Can anyone help me get some idea? Thanks in advance

推荐答案

当您创建一个空白类时,编译器会给它一个默认构造函数 - 一个不带参数的构造函数。这就好像你把课程写成:

When you create a "blank" class, it is given a default constructor by the compiler - one which takes no parameters. It's as if you wrote the class as:
public class MyClass
   {
   public MyClass() {}
   }

但是默认构造函数不是唯一可以拥有的构造函数 - 您也可以使用带参数的构造函数:

But a default constructor isn't the only one you can have - you can have constructors with parameters as well:

public class MyClass
   {
   private int[] myData;
   public MyClass(int count)
      {
      myData = new int[count];
      }
   }

在这种情况下,构造函数在内部数组中分配所需的整数数。

然后你创建类实例就像这个:

In this case, the constructor allocates the required number of integers in the internal array.
And you then create your class instance like this:

int i = int.Parse(myTextBox.Text);
MyClass mc = new MyClass(i);


它创建一个实例classClass,由于Class不是关键字class,这是可能的。它将在您正在查看的代码中的其他位置定义。

Class 的构造函数采用类型 i 兼容的参数。 Class 构造函数然后使用 i 做一些我们在这个小片段中看不到的东西。再次,看一下原始项目中的 Class 定义代码。

最后, Class 的新实例将被丢弃,除非有一个此处未显示的赋值。
It creates an instance of class "Class", which is possible due to "Class" not being the keyword "class". It will be defined somewhere else in the code you're looking at.
The constructor for Class takes an argument whose type i is compatible to. The Class constructor then does something with i that we cannot see in this tiny snippet. Again, have a look at the Class definition code in the originating project.
Finally, the new instance of Class is thrown away unless there's an assignment that's not shown here.


表示:创建类的实例 Class ,调用单个参数类 Class '构造函数,参数值 i

参见构造函数(C#编程指南) [ ^ ]。
Means: "Create an instance of the class Class, calling the single parameter class Class' constructor with argument value i".
See Constructors (C# Programming Guide)[^].


这篇关于C#中的新类(i)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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