通过循环遍历数组来分配类变量 [英] Assigning Class Variables by looping through an array

查看:74
本文介绍了通过循环遍历数组来分配类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





自学C#。我在下面有一个简单的程序,我定义了一个名为Box的类。我想添加对象 - 一个正方形和一个矩形,并为对象的长度和宽度变量赋值。



我想最终读取对象的名称,长度和宽度从一个文件,但我硬编码字符串[,]现在可以使用。



请说明以下内容:



1)类变量_length和_width标准约定的语法是什么?任何其他语法或约定问题?



2)int.Parse没有问题。 int.TryParse给我一个错误(见下面代码块中的注释)



3)如何从数组中读取对象名,这里数据为[i,0并使用它而不是硬编码

square._lenght = data [0,1]或rectangle._length = data [1.1]

所以逻辑是

data [i,0] ._ lenght = data [i,1]----无法编译。



4)后来,当我从csv文件中读取时,我可能不知道文件中有多少对象或对象名称是什么 - 尽管每个对象名称都是唯一的。

例如,数组在文件中阅读时创建的内容可能如下:



data =



{square, 6,6},

{anothersquare,10,10}

{smallrectangle,3,4}

{bigsquare,20,20}



那么我将如何发起(这是正确的术语?)具有逻辑的每个对象如下:



for(int i = 0; i< data.Rank; i ++)

箱数据[i,0] =新箱子();



感谢您的时间,



Tim



Hi,

Self teaching C#. I have a simple program below where I define a Class called Box. I want to add objects - a square and a rectangle and assign values to the object's length and width variable.

I want to eventually read the objects name, length and width from a file, but I hard coded a string [,] to work with now.

Please address the following:

1) Is the syntax for the class variables "_length" and "_width" standard convention? Any other syntax or convention issues?

2) int.Parse works no issues. int.TryParse gives me an error (see comment in code block below)

3) How can I read the object name from an array, here data[i,0] and use that instead of hard coding
"square._lenght = data[0,1]" or "rectangle._length = data [1.1]"
so logic is
"data[i,0]._lenght = data[i,1]"---- which does not compile.

4) Later, when I read from the csv file I may not know how many objects are in the file or what are the object names- although each object name will be unique.
For example, the array created when reading in the file may look like:

data =

{"square","6","6"},
{"anothersquare", "10","10"}
{"smallrectangle","3","4"}
{"bigsquare", "20","20"}

So how would I initiate (is that the correct jargon?) each object with logic as follows:

for (int i = 0; i < data.Rank; i++)
Box data[i,0] = new Box();

Thanks for your time,

Tim

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            Box square = new Box();
            Box rectangle = new Box();

            string boxType = null;
            double boxTypeLength = 0;
            double boxTypeWidth = 0;

            string [,] data = new string [,]
            {
                {"square", "5", "5"},
                {"rectangle", "4", "6"}
            };

            for (int i = 0; i < data.Rank; i++)
            {
                boxType = data[i,0];
                boxTypeLength = double.Parse(data[i,1]);
                boxTypeWidth = double.TryParse(data[i, 2]);    //.TryParse gives "Error 1 No overload for method 'TryParse' takes 1 arguments"


                boxType._length = boxTypeLength;              //intent is: square._length = boxTypeLength  then loop and assign rectangle._length = boxTypeLength
                boxType._width = boxTypeWidth;                //intent is: square._width = boxTypeWidth  then loop through rest of array


                Console.Write("The " + boxType + "'s area is: ");
                boxType.CalcArea();  		             //square.CalcArea()  then loop                
            }

            Console.Read();
	}
   }
}


Box.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication10
{
    class Box
    {
        public double _length;
        public double _width;

        public void CalcArea()
        {
            double area = _length * _width;
            Console.WriteLine(area);
        }
    }
}

推荐答案

你最大的问题,一个误解,就是你是尝试使用字符串,而不是使用数据本身。您的数据不应是字符串数组{string,string,string}。相反,它应该是一个类/结构{string,uint,uint}或类似的东西。您的错误消息是自解释的:您无法解析字符串数组,但您可以解析单个流。但解析的整个想法是没有意义的。



您可能会说:但后来我想将我的数据存储在一个文本文件中并从中初始化我的盒子。但是1)你应该将这个问题从数据初始化中分离出来:首先获取数据(不是文本数据),然后从数据中初始化你的盒子; 2)您不需要处理文本数据并直接解析这些数据;一切都已经完成或者你。



要利用第二种方法,您可以使用XML(或JSON,如果需要)持久性和数据合同 http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ]。



您不需要自己处理XML或任何文件。基于数据联系人的序列化器只是将任何对象图存储在任何文件或流中;然后你可以像以前那样恢复它。这种方法最容易使用且非侵入性:您不必实现任何接口,从任何特定类型派生您的数据类,什么都不是。您只需添加一些不会影响其余功能的属性;你只需要告诉系统你想在合同中拥有什么。请查看我过去的答案:

创建属性文件...... [ ^ ],

http://msdn.microsoft.com/en-us /library/ms733127.aspx [ ^ ],

解析json字符串数组 [ ^ ]。



-SA
You biggest problem, a misconception, is that you are trying to work with strings, instead of working with data itself. Your data should not be array of strings {string, string, string}. Instead, it should be a class/structure {string, uint, uint}, or something like that. Your error messages are self-explained: you cannot parse array of strings, but you can parse a single stream. But the whole idea of parsing makes no sense.

You may say: "but later I want to store my data in a text file and initialize my boxes out of it". But 1) you should isolate this problem from initialization from data: get data (not text data) first, then initialize your boxes from data; 2) you don't need to deal with text data and parse this data directly; everything is already done or you.

To leverage the second approach, you can use XML (or JSON, if you want) persistence and Data Contract: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

You don't need to deal with XML or with any files by yourself. Data Contact based serializer simply stores any object graph in any file or a stream; and later you can restore it the way it was before. This approach is the easiest to use and very non-intrusive: you don't have to implement any interfaces, derive your data classes from any certain types, nothing. All you need is to add some attributes which cannot affect the rest of your functionality; you just need to tell the system what do you want to have in a contract. Please see my past answers:
Creating property files...[^],
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^],
deseralize a json string array[^].

—SA


我强烈建议阅读.NET Book Zero [ ^ ],它对类和结构进行了非常清晰的介绍,以及如何正确使用它们。
I would strongly recommend reading .NET Book Zero[^] which gives a very clear introduction to classes and structs, and how to use them properly.


这篇关于通过循环遍历数组来分配类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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