如何在程序中使用构造函数的参数 [英] How to use parameters of constructor in program

查看:75
本文介绍了如何在程序中使用构造函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个方法,我将参数传递给构造函数,该方法在调用方法时返回generic.list.collection



现在我在main方法中调用此方法。我需要将generic.list.collection的一个参数与main方法中的另一个变量进行比较。



我该怎么做?如何在我的程序中用三个构造函数的参数来比较???





Hi,

I have a method in which I am passing arguments to a constructor and the method returns the generic.list.collection when the method is called

Now I am calling this method in main method. I need compare one of the arguments of generic.list.collection with another variable in main method.

How can I do this??. How can I take one argument of constructor out of three in my program to compare???


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Collections;
//using SCANLA.Common;
using System.Text.RegularExpressions;

namespace ConsoleApplication13
{

    
    class Program
    {


        static void Main()
        {
            var p = new Program();
            p.Bar();
        }

        void Bar()
        {
            
           
            List<MsgIdTimeStampMap> CANMsgIdList = new List<MsgIdTimeStampMap>();
           
           CANMsgIdList=  ReadLogFile(@"\\global.scd.scania.com\home\se\121\valhbc\Desktop\log files\log file with orange\logfile.asc");

           
           
        }
        private List<MsgIdTimeStampMap> ReadLogFile(string dataLogFile)
        {
            string[] fileContents = null;
            List<MsgIdTimeStampMap> CANMsgIdList = new List<MsgIdTimeStampMap>();

            try
            {
                // Open and read the entire Data Log File contents.
                fileContents = File.ReadAllLines( dataLogFile);
            }
            catch (Exception ex)
            {
                throw new Exception("The Input log file was not found or is not in correct format\nDetails: " + ex.Message);
            }



            if (fileContents == null)
                throw new Exception("The Input log file was not found or is not in correct format");

            // Process each line of the Data Log File and filter out the CAN Msg Id's corresponding to each CAN Bus.
            for (int Index = 0; Index < fileContents.Length; Index++)
            {
                string CANMsgId = string.Empty;
                string timeStamp = string.Empty;
                string[] spaceSeperator = new string[] { " " };
                string[] lineWords = (fileContents[Index].Trim()).Split(spaceSeperator, StringSplitOptions.RemoveEmptyEntries);

                // If the number of words in a line is less than 3 then its not a valid entry.
                if (lineWords.Length < (Constants.CAN_MSGID_HEX_INDEX + 1))
                    continue;

                // If a CAN Msg Id is valid, it should end with 'x'. If it doesnot end with 'x',
                // then skip the entry and go to the next line of log file
                if (lineWords[Constants.CAN_MSGID_HEX_INDEX].EndsWith("x"))
                {
                    CANMsgId = lineWords[Constants.CAN_MSGID_HEX_INDEX].TrimEnd('x');
                    timeStamp = lineWords[Constants.CAN_TIMESTAMP_INDEX];
                }
                else
                    continue;

                // Check the format of the CAN Msg Id, whether Hex or not.
                if (Regex.IsMatch(CANMsgId, Constants.CAN_MSGID_HEX_FORMAT_REGREX))
                {
                    Buses CANBus = (Buses)Enum.Parse(typeof(Buses), (lineWords[Constants.CAN_BUSID_INDEX]));
                    CANMsgIdList.Add(new MsgIdTimeStampMap(CANBus, CANMsgId, timeStamp));
                }
            }

            return CANMsgIdList;

        }

        

         }
      ]







这是我的构造函数






this is my constructor

public class MsgIdTimeStampMap
        {
            string msgId;
            string timeStamp;
            public Buses Bus { get; set; }


            public string MsgId
            {
                get
                {
                    if (!String.IsNullOrEmpty(msgId))
                        return msgId.ToUpper();
                    else
                        return string.Empty;
                }

                set { msgId = value; }
            }

            public string TimeStamp
            {
                get
                {
                    if (!String.IsNullOrEmpty(timeStamp))
                        return timeStamp;
                    else
                        return string.Empty;
                }

                set { timeStamp = value; }
            }

            public MsgIdTimeStampMap(Buses bus, string msgId, string timeStamp)
            {
                this.Bus = bus;
                this.msgId = msgId;
                this.timeStamp = timeStamp;

            }
            public override string ToString() // Equals,GetHash also there.here I am using ToString
            {
                return this.MsgId + ", " + this.Bus + ", " + this.TimeStamp;
            }

        }





在此代码中,在main方法和ReadLogFile方法中调用ReadLogFile方法返回构造函数的3个参数到main方法。在main方法中如何访问构造函数的一个参数进行比较???







谢谢

John



In this code ReadLogFile method is called in main method and ReadLogFile method returns 3 arguments of constructor to main method. In the main method how can I access one argument of Constructor for comparing???



Thanks
John

推荐答案

看来你正试图在Bar()方法中捕获CANMsgIdList中的返回值。虽然它似乎没有在类或Bar()方法中声明它。



一旦你发现它,你可以用foreach或for i遍历列表并进行比较。如果你只想要第二个参数(或特定的)你也可以引用它CANMsgIdList [1]。
It appears you are trying to catch the return values in CANMsgIdList in the Bar() method. though it doesn't appear you have declared it yet in the class or the Bar() method.

Once you catch it you can iterate through the list with a foreach or a for i and do your comparisons. If you only want the 2nd argument (or specific) you can also reference it CANMsgIdList[1] as well.


现在你在'Bar方法中声明并实例化CANMsgIdList:
Right now you declare, and instantiate, CANMsgIdList in the 'Bar method:
List<MsgIdTimeStampMap> CANMsgIdList = new List<msgidtimestampmap>();</msgidtimestampmap>

所以CANMsgIdList是一个私有变量,永远不会在'Bar的范围之外访问。



您还在'ReadLogFile方法中声明并实例化具有相同名称的变量:

So CANMsgIdList is a private variable that will never be accessible outside the scope of 'Bar.

You also declare, and instantiate, a variable with the same name in the 'ReadLogFile method:

List<MsgIdTimeStampMap> CANMsgIdList = new List<MsgIdTimeStampMap>();

该变量不能在'ReadLogFile范围之外访问。



虽然C#编译器如果它在不同的词法范围内找到相同类型和名称的变量(并且ReSharper也不会标记它),则不会抛出错误,具有这种重复,imho,混淆代码的方法,以及将来的错误。



如果要在Main过程中或在Application中的其他方法中访问CANMsgIdList的实例,请声明并实例化它一次在程序/类的范围内。



例如:

That variable will not be accessible outside the scope of 'ReadLogFile.

While the C# compiler will not throw an error if it finds variables of the same Types, and Names, in different lexical scopes (and ReSharper won't flag it either), having that kind of duplication is, imho, a recipe for confusing code, and future errors.

If you want to access the instance of CANMsgIdList in your Main procedure, or in other methods in your Application, declare, and instantiate, it once in the scope of the Program/Class.

For example:

// in Program/Class scope:
List<MsgIdTimeStampMap> CANMsgIdList;

private void Bar()
{              
    // initialize CANMsgIDList
    CANMsgIdList = new List<msgidtimestampmap>();

    ReadLogFile(
      @"\\global.scd.scania.com\home\se\121\valhbc\Desktop\log  
      files\log file with orange\logfile.asc");
}</msgidtimestampmap>

如果你走这条路,你可以修改'ReadLogFile方法返回void:

If you go this route you can then modify the 'ReadLogFile method to return void:

private void ReadLogFile(string dataLogFile)

并消除方法中的return语句:现在,'ReadLogFile中的'Add方法'实例将直接在程序/类中所有方法可用的CANMsgList实例上运行。



然而,这只是一种方法:将'CANMsgIdListas参数的实例传递给'ReadLogFile,并让'ReadLogFile在它之后返回相同的实例没有任何问题。 充实。



作为参数传递结构并返回它们的形式程度通常受到需要重新调整的程度的影响 - 使用方法。



在创建方法和字段,结构等时定义类型访问修饰符是一个非常好的主意,它会使你的代码更多可读,并且帮助很高与范围相关的轻微问题,如此处的问题。 '公共和'私人费用你很少:)

and eliminate the return statement in the method: now the instance 'Add method in 'ReadLogFile will operate directly on the instance of CANMsgList available to all methods in the Program/Class.

However, that's just one approach: there would be nothing wrong with passing the instance of 'CANMsgIdListas a parameter into 'ReadLogFile, and having 'ReadLogFile return the same instance after it has been "fleshed-out."

The extent of "formality" in passing in structures as parameters, and returning them, is most often influenced by the extent you need to re-use methods.

It's a very good idea, imho, to define Type access modifiers as you create methods and fields, structs, etc. It makes your code much more readable, and helps highlight issues related to scope, like the issue here. 'public and 'private cost you very little :)


这篇关于如何在程序中使用构造函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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