从具有“禁止”列表的列表中禁止变量

时间:2018-11-10 14:06:24

标签: c# unity3d

如何通过将变量添加到“已禁止”变量列表中来禁止从列表中删除变量?

我希望能够输入一个字符串。将该字符串与文件夹中的文件名进行比较。如果匹配,则读取文件。如果我再次输入相同的字符串,则不应再次读取该文件。在那里,我希望有一个“禁止”字符串列表,在键入该列表时会对其进行检查,以避免再次读取该文件。

我尝试了几种方法,但没有到达目的地。下面是我最后一次尝试的示例。

什么是最好的方法?

public class test 
{

 string scl= "test3";

 List <string> lsf,lso;

 void Start () 
 {
  lsf=//file names 
   new List<string>();

  lso=//files open 
   new List<string>();

  lsf.Add("test0");
  lsf.Add("test1");
  lsf.Add("test2");
  lsf.Add("test3");
  lsf.Add("test4");

  lso.Add("idhtk49fngo");//random string        
 }

void Update () 
{
 if
 (
  Input.GetKeyDown("a")
 )
 {
  for
  (
   int i=0;
   i<lsf.Count;
   i++
  )
  {
   if(lsf[i]==scl)
   {
    Debug.Log
    (i+" is read");

    for
    (
     int j=0;
     j<lso.Count;
     j++
    )
    {

     //how can i avoid reading
     //lsf[3] here the second time
     //"a" is pressed (by having "test3" 
     //added to a "ban" list (lso) )

     if(scl!=lso[j])
     {

      lso.Add(lsf[i]);

     }
    }
   }
  }
 }
}

4 个答案:

答案 0 :(得分:0)

我会这样建议:​​

public static List<string> openedFiles = new List<string>();
public static string ReadFileAndAddToOpenedList(string path)
{
    if (openedFiles.Contains(path))
        throw new Exception("File already opened");
        // Instead of throwing exception you could for example just log this or do something else, like:
        // Consolle.WriteLine("File already opened");
    else
    {
        openedFiles.Add(path);
        return File.ReadAllText(path);
    }
}

这个想法是-在每次读取文件时,将文件添加到列表中,因此您可以在每次尝试读取文件时检查是否已读取(或打开)文件。如果是,则引发异常(或执行其他操作)。否则读取文件。

答案 1 :(得分:0)

您可以使用自己的类来代替它成为字符串列表

public class MyFile
{
    public string Name;
    public bool isOpen;

    public MyFile(string name)
    {
        Name = name;
        isOpen = false;
    }
}

List<MyFile> lsf = new List<MyFile>()
{
    new MyFile("test0"),
    new MyFile("test1"),
    new MyFile("test2"),
    new MyFile("test3"),
    new MyFile("test4")
};

比当您读取文件时将isOpen设置为true

MyFile[someIndex].isOpen = true;

稍后您可以检查一下

// E.g. skip in a loop
if(MyFile[someIndex]) continue;

您还可以使用Linq来获取仅未读文件的列表:

var unreadFiles = lsf.Select(f => f.Name).Where(file => !file.isOpen);

答案 2 :(得分:0)

Michael的答案是到达这里,但是可以使用更合适的馆藏来跟踪打开的文件来进行改进;如果要唯一性,请使用集合而不是列表:

 HashSet<string> openedFiles = new HashSet<string>();

 public static bool TryFirstRead(
     string path,
     out string result)
 {
     if (openedFiles.Add(path))
     {
          result = File.ReadAllText(path);
          return true;
     }

     result = null;
     return false;
 }

此外,我会避免抛出vexing exceptions。为用户提供一种友好的方式来了解是否已读取文件,而不必让他们最终不得不使用异常作为流控制机制。

答案 3 :(得分:0)

我不明白,但是如果您想替换另一个列表中的值。 您可以使用列表索引使用删除的值创建一个新列表。 String list1 = {"hi", "hello", "World"}; String list2 = {"bye", "goodbye", "World"}; List1[1] = list2[1];

相关问题