【问题标题】:File.exists giving a null reference exception instead of returning false. c# [duplicate]File.exists 给出一个空引用异常而不是返回 false。 c# [重复]
【发布时间】:2019-03-29 01:35:13
【问题描述】:
if(File.Exists(Application.persistentDataPath + "/users/" + Input.GetComponent<Text>().text + ".dat"))

此行在找不到文件时总是会导致空引用异常,而不是返回 false。

【问题讨论】:

  • 其实不是的,里面的代码给出了空引用异常,请调试你的代码找出原因
  • 从调用中提取 Application.persistentDataPathInput.GetComponent&lt;Text&gt;() 并在调试器中检查两者的值。
  • 当我点击错误消息时,它给出了这行代码的错误,并且没有经过这个 if 语句,其他代码甚至都不会触发
  • 再一次,File.Exists 不是问题,它里面的代码是
  • 当您尝试访问 null 对象的成员(属性、方法、字段)时,会发生 NullReferenceException。因此,其中之一是 null => ApplicationInputGetComponent&lt;Text&gt;()

标签: c# nullreferenceexception system.io.file


【解决方案1】:

File.Exists 没问题。考虑像这样修复您的代码

    if (Application.persistentDataPath != null && Input != null && Input.GetComponent<Text>() != null && Input.GetComponent<Text>().text != null)
    {
        if(File.Exists(Application.persistentDataPath + "/users/" + Input.GetComponent<Text>().text + ".dat"))

【讨论】:

  • @RufusL 我刚刚修复了它们。 cmets 中的建议足以解决这个问题,但我看到提问者并不真正理解问题
  • 你的最后一个条件应该是Input.GetComponent&lt;Text&gt;() != null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 2016-04-29
相关资源
最近更新 更多