【问题标题】:How to Access Variable From One Class in Another Class? [C#]如何从另一个类中的一个类访问变量? [C#]
【发布时间】:2011-10-22 15:36:37
【问题描述】:

所以我正在开发一个 C# 程序,它接收目录中的一组分隔文本文件并解析文件中的信息(即文件路径、文件名、相关关键字)。这就是示例文件的样子...

C:\Documents and Settings\workspace\Extracted Items\image2.jpeg;image0;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image3.jpeg;image1;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image4.jpeg;image2;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image5.jpeg;image3;keyword1, keyword2, keyword3, keyword4

好吧,我的合作伙伴给了我一些执行此操作的代码,但我需要能够访问列表变量,该变量填充在其中一种方法中。这是代码:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp
{
    public class FileIO
    {
        private static Boolean isTextFile;
        private static Boolean debug;

        private static int semiColonLoc1, semiColonLoc2, dblQuoteLoc1;
        private static int lineLength, currentTagLength;
        private static int numImages;
        private static int numFiles;
        public static List<Image> lImageSet;

        /*
          ****************************************************
          ***** CHANGE THIS PATH TO YOUR PROPERTIES FILE *****
          ****************************************************
        */
        private static readonly string propertiesFileDir = "C:/Documents and Settings/properties.properties";

        public PropertyKeys getProperties(string propertiesFileDir, PropertyKeys aPropertyKeys)
        {
            string line;
            string directoryKey = "extractedInfoDirectory";
            string debugKey = "debug2";
            string directory;

            Boolean isDirectoryKey;
            Boolean isDebugKey;

            System.IO.StreamReader file = new System.IO.StreamReader(propertiesFileDir);

            while ((line = file.ReadLine()) != null)
            {

                isDirectoryKey = false;
                isDebugKey = false;

                //  If the current line is a certain length, checks the current line's key
                if (line.Length > debugKey.Length)
                {
                    isDebugKey = line.Substring(0, debugKey.Length).Equals(debugKey, StringComparison.Ordinal);

                    if (line.Length > directoryKey.Length)
                    {
                        isDirectoryKey = line.Substring(0, directoryKey.Length).Equals(directoryKey, StringComparison.Ordinal);
                    }
                }

                //  Checks if the current line's key is the extractedInfoDirectory
                if (isDirectoryKey)
                {
                    directory = line.Substring(directoryKey.Length + 1);
                    aPropertyKeys.setExtractedInfoDir(directory);
                }

                //  Checks if the current line's key is the debug2
                else if (isDebugKey)
                {
                    debug = Convert.ToBoolean(line.Substring(debugKey.Length + 1));
                    aPropertyKeys.setDebug(debug);
                }
            }

            return aPropertyKeys;
        }

        public void loadFile()
        {

            string line;
            string tempLine;
            string fileToRead;
            string fileRename;
            string imagePath, imageName, imageTags, currentTag;
            string extractedInfoDir;
            string extension;
            string textfile = "txt";
            string[] filePaths;

            PropertyKeys aPropertyKeys = new PropertyKeys();

            //  Finds extractedInfoDir and debug values
            aPropertyKeys = getProperties(propertiesFileDir, aPropertyKeys);
            extractedInfoDir = aPropertyKeys.getExtractedInfoDir();
            debug = aPropertyKeys.getDebug();

            //  Finds all files in the extracted info directory
            filePaths = Directory.GetFiles(extractedInfoDir);
            numFiles = filePaths.Length;

            //  For each file in the directory...
            for (int n = 0; n < numFiles; n++)
            {
                int k = filePaths[n].Length;

                // Finds extension for the current file
                extension = filePaths[n].Substring(k - 3);

                // Checks if the current file is .txt
                isTextFile = extension.Equals(textfile, StringComparison.Ordinal);

                // Only reads file if it is .txt
                if (isTextFile == true)
                {

                    fileToRead = filePaths[n];
                    Console.WriteLine(fileToRead);
                    System.IO.StreamReader file = new System.IO.StreamReader(fileToRead);

                    //  Reset variables and create a new lImageSet object
                    lImageSet = new List<Image>();

                    line = ""; tempLine = ""; imagePath = ""; imageName = ""; imageTags = ""; currentTag = "";
                    semiColonLoc1 = 0; semiColonLoc2 = 0; dblQuoteLoc1 = 0; lineLength = 0; currentTagLength = 0; numImages = 0;

                    while ((line = file.ReadLine()) != null)
                    {

                        //  Creates a new Image object
                        Image image = new Image();
                        numImages++;

                        lineLength = line.Length;

                        //  Finds the image path (first semicolon delimited field)
                        semiColonLoc1 = line.IndexOf(";");
                        imagePath = line.Substring(0, semiColonLoc1);
                        image.setPath(imagePath);

                        tempLine = line.Substring(semiColonLoc1 + 1);

                        //  Finds the image name (second semicolon delimited field)
                        semiColonLoc2 = tempLine.IndexOf(";");
                        imageName = tempLine.Substring(0, semiColonLoc2);
                        image.setName(imageName);

                        tempLine = tempLine.Substring(semiColonLoc2 + 1);

                        //  Finds the image tags (third semicolon delimited field)
                        imageTags = tempLine;

                        dblQuoteLoc1 = 0;

                        // Continues to gather tags until there are none left
                        while (dblQuoteLoc1 != -1)
                        {
                            dblQuoteLoc1 = imageTags.IndexOf("\"");
                            imageTags = imageTags.Substring(dblQuoteLoc1 + 1);
                            dblQuoteLoc1 = imageTags.IndexOf("\"");

                            if (dblQuoteLoc1 != -1)
                            {
                                //  Finds the next image tag (double quote deliminated)
                                currentTag = imageTags.Substring(0, dblQuoteLoc1);
                                currentTagLength = currentTag.Length;

                                //  Adds the tag to the current image
                                image.addTag(currentTag);
                                image.iNumTags++;
                                imageTags = imageTags.Substring(dblQuoteLoc1 + 1);
                            }
                        }

                        //  Adds the image to the current image set
                        lImageSet.Add(image);

                    }

                    //  Prints out information about what information has been stored
                    if (debug == true)
                    {
                        Console.WriteLine("Finished file " + (n + 1) + ": " + filePaths[n]);

                        for (int i = 0; i < numImages; i++)
                        {
                            Console.WriteLine();
                            Console.WriteLine("***Image " + (i + 1) + "***");
                            Console.WriteLine("Name: " + lImageSet.ElementAt(i).getName());
                            Console.WriteLine("Path: " + lImageSet.ElementAt(i).getPath());
                            Console.WriteLine("Tags: ");

                            for (int j = 0; j < lImageSet.ElementAt(i).iNumTags; j++)
                            {
                                Console.WriteLine(lImageSet.ElementAt(i).lTags.ElementAt(j));
                            }

                        }
                    }

                    file.Close();

                    //  Changes destination file extension to .tmp
                    fileRename = fileToRead.Substring(0, fileToRead.Length - 4);
                    fileRename += ".tmp";

                    //  Changes file extension to .tmp
                    System.IO.File.Move(fileToRead, fileRename);
                }

                //  Not a text file
                else
                {
                    Console.WriteLine("Skipping file (no .txt extension)");
                }
            }
            Console.ReadLine();
        }
    }
}

但是,我不想过多地弄乱他的代码,因为他暂时不在这里修复任何东西。所以我只想知道如何在我的另一个类中从他的代码中访问lImageSet。我希望它会类似于使用FileIO fo = new FileIO 实例化 FileIO,然后执行类似fo.loadFile().lImageSet 的操作,但事实并非如此。有什么想法吗?

【问题讨论】:

  • 为什么所有成员都是静态的?如果您有该类的多个实例...?

标签: c# class scope


【解决方案1】:

因为lImageSet就是static,所以不需要实例化FileIO来获取。

试试FileIO.lImageSet

【讨论】:

    【解决方案2】:

    loadFile 方法返回void,因此您不能使用点运算符从中访问任何内容。你会想做这样的事情:

    FileIO fo = new FileIO();
    fo.loadFile();
    List<Image> theImages = FileIO.lImageSet;
    

    【讨论】:

    • +1 提醒我我没有把 FileIO obj 的加载。
    【解决方案3】:

    该列表是静态的,因此您可以使用类的名称来访问它:

    List<Image> theList = FileIO.lImageSet
    

    【讨论】:

      【解决方案4】:

      它是公开的——所以在您的课堂上,您可以通过以下方式访问它:

      FileIO.lImageSet
      

      要获取其中的值,只需将其迭代为:

      //from FishBasketGordo's answer - load up the fo object
      FileIO fo = new FileIO();
      fo.loadFile();
      
      foreach(var img in FileIO.lImageSet) {
        //do something with each img item in lImageSet here...
      }
      

      编辑:我以 FishBasketGordo 的回答为基础,将他的 loadFile() 调用合并到我的示例中。

      【讨论】:

      • 所以在 foreach 循环中,如果您注意到在 OP 中贴在底部的代码中他有 Console.WriteLine("Name: " + lImageSet.ElementAt(i).getName()); ,我无法访问“ElementAt”方法,那么我该如何访问我想要在列表中的位置?
      • Nvm,我能弄明白。感谢您以及其他所有人的帮助!我会给你答案,因为你加倍努力并在那里添加了 foreach。 :)
      • 谢谢 - 很高兴我能帮上忙。
      【解决方案5】:

      由于 lImageSet 是静态的,您需要做的就是访问它:

      List&lt;image&gt; theList = FileIO.lImageSet;

      无需实例化对象即可获得对该字段的引用。

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-09-30
        相关资源
        最近更新 更多