自定义类库作为数组 C#
我正在使用 C# 中的一个类库,它有自己的方法,我想从这个库创建一个数组,但是当我在主程序中调用它时,我看不到它的方法。
public class ClassLibrary1
{
public int num;
public ClassLibrary1 ()
{
}
public void Readdata()
{
Console.Write("write a number ");
num = int.Parse(Console.ReadLine());
}
}
program.cs:
ClassLibrary1[] arraynumbers = new ClassLibrary1[5];
arraynumbers.Readdata();
我无法使用Readdata()
。
谁能帮助我吗?
I'm working with a class library in C# with its own methods and I want to create an array from this library, but I when call it in the main program I cant see its methods.
public class ClassLibrary1
{
public int num;
public ClassLibrary1 ()
{
}
public void Readdata()
{
Console.Write("write a number ");
num = int.Parse(Console.ReadLine());
}
}
program.cs :
ClassLibrary1[] arraynumbers = new ClassLibrary1[5];
arraynumbers.Readdata();
And I can't use Readdata()
.
Can anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想调用类中的方法,则必须至少创建一个实例。事实上,您所做的就是创建一个空引用数组,然后尝试在该数组上调用您的方法。这是您可以做到的一种方法。
If you want to call methods in your class, you'll have to create at least one instance. As it is, all you've done is create an array of null references, and then attempt to call your method on the array. Here's one way you could do it.
您不能按照您的方式使用
Readdata
,因为ClassLibrary1[]
是一个 ARRAY 对象,而不是ClassLibrary1
对象,其中你的方法已经定义了。你必须做这样的事情:
You can't use
Readdata
the way you've put it becauseClassLibrary1[]
is an ARRAY object, not aClassLibrary1
object, in which your method is defined.You'd have to do something like this instead:
Readdata()
是ClassLibrary1
实例的方法,而不是保存ClassLibrary1
实例的数组。Readdata()
is a method of theClassLibrary1
instance, not the array that holdsClassLibrary1
instances.不能在该类的集合上调用在类上定义的方法。如果您想在集合上使用方法,请考虑创建一个扩展方法:
第一个参数中的“this”关键字允许您“假装”此方法位于“ClassLibrary1[]”类型或数组上。即扩展该类型。
Methods that are defined on a class may not be called on a collection of that class. If you want to use a method on a collection, consider making an extension method:
The "this" keyword in the first parameter allows you to "pretend" this method is on a type of "ClassLibrary1[]" or array. I.e. extending that type.