如何一次设置一个类的多个属性的值? [英] How to set values of multiple attributes of a class at a time ?

查看:205
本文介绍了如何一次设置一个类的多个属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#窗体表格



这是我的问题:



假设我有一个简单的课程:



Class Animal

{

int height;

DateTime date_of_birth;

浮动年龄;

int max_age;

}

< b>

我在文件中有以下数据:



---------- ------------
第一只动物


10

1997

23.4

12


第二只动物


12

2017

33.9

21



和儿子......

------ ----------------



我的问题是:



我想将我的类实例化五次以上并从上面显示的文件中设置属性。



手动创建每个类并以正确的方式逐个设置属性?



或者还有其他有效的方法可以做到这一点。即避免硬编码。





任何类型的建议都是apreciated

I am working on C# windows form

Here is my problem:

Suppose I have a simple class:

Class Animal
{
int height;
DateTime date_of_birth;
float age;
int max_age;
}

And i have the following data in a file:


----------------------
for first animal
10
1997
23.4
12

for second animal
12
2017
33.9
21

and son on...
----------------------

My problem is:

I want to instantiate my class more than five times and set the attributes from the file shown above.

Is manually creating each class and setting the attribute one by one the right way ?

OR there is any other efficient way to do this . i.e. avoiding hard coding.


Any kind of suggestions would be apreciated

推荐答案

因此,您需要为每只动物创建一个Animal对象。根据文件格式注释的答案,您可以使用构造函数轻松实例化一个类。



So you need to create an Animal object for each animal you have. Depending on the answer to the comment for file formatting, you can easily instantiate a class simply using a constructor.

class Animal
{
    int height;
    DateTime date_of_birth;
    float age;
    int max_age;

    public Animal(int height, DateTime date_of_birth, float age, int max_age) {
        this.height = height;
        this.date_of_birth = dob;
        this.age = age;
        this.max_age = max_age;
    }
}





然后用您的数据填写值,您可以从任何文件中执行此操作有(即XmlDocument,TextReader)。应该能够在每个节点或行中读取并通过它进入循环以根据需要创建动物对象。



Then fill in the values with your data, which you would do from whatever file you have (i.e. XmlDocument, TextReader). Should be able to read in each node or line and through it into a loop to create animal objects as needed.

Animal first = new Animal(5, new DateTime(), 5, 10);
Animal second = new Animal(2, new DateTime(), 3, 11);


是属性,而不是属性。在.NET中,属性意味着完全不同的东西。使用正确的术语,否则你会混淆那些试图帮助你的人。
The are properties, not attributes. In .NET, "attributes" means something completely different. Use the correct terminology, otherwise you're going to confuse people trying to help you.


创建类的属性和设置这些属性的参数化构造函数。实例化类时,调用构造函数并传递其中的值以初始化属性。
Create properties of the class and a parameterized constructor which sets these properties. While instantiating the class call the constructor and pass the values in it to initialize the properties.


这篇关于如何一次设置一个类的多个属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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