3

为什么这段代码(在我的表单_Load()事件中):

FileVersionInfo vi = FileVersionInfo.GetVersionInfo(_fullPath);
String VersionInfo = vi.FileVersion;
if (VersionInfo.Trim().Equals(String.Empty)) {
    VersionInfo = NO_VERSION_INFO_AVAILABLE;
}
textBoxVersionInfo.Text = VersionInfo;

...给我以下错误消息什么时候VersionInfo == ""是真的?

System.NullReferenceException 未处理消息=对象引用未设置为对象的实例。*

4

5 回答 5

7

你应该String.IsNullOrEmpty在这里使用方法。见 MSDN

if (String.IsNullOrEmpty(VersionInfo)) {
    VersionInfo = NO_VERSION_INFO_AVAILABLE;}
于 2012-04-13T19:53:10.860 回答
5

Well, since I was getting a ridiculous number of down votes on my other question, here it is again in a more blunt and less lighthearted fashion:

  • null represent the lack of an object; and
  • all strings are objects; thus
  • there is no string, of any length, which is null; thus
  • an empty string is never null.

That's it, nothing more. Examine the stack-trace and/or attach a debugger to find out where the null (which is not an empty string) is coming from.

The exception is the result of using expr.somePropertyFieldOrMethod where expr evaluates to null1 hence the Null Reference Exception.

It is the job of you, the developer, to find out which expr was null instead of waiting to see what others suggest might be wrong. As such, I am closing this as "too localized" after answering the question in the title, which is the only question present.

(As in my previous answer, I note that textBoxVersionInfo being null could cause this exception, even when VersionInfo == "" is true. The other alternative is, of course, that that VersionInfo does not represent the empty string.)


1 Technically this exception could be raised arbitrarily, perhaps justified in an Extension Method. However, raising this exception wantonly is not common or good practice or found in the .NET framework and is thus generally a dismissible cause when debugging.

于 2012-04-13T19:56:08.360 回答
2

如果VersionInfo is NULL为真,则VersionInfo.Trim()将给出错误。

请使用String.IsNullOrEmpty.

如果 VersionInfo 为空,那么您可以使用

if(VersionInfo == null)

或者

String.IsNullOrEmpty(VersionInfo)

于 2012-04-13T19:52:58.050 回答
2

有一种null安全的方法可以做到这一点:而不是

VersionInfo.Trim().Equals(String.Empty)

string.IsNullOrWhiteSpace(VersionInfo)

如果为null,它不会崩溃,如果修剪导致空字符串 VersionInfo,它将返回true 。VersionInfo

于 2012-04-13T20:00:16.147 回答
1

After your response to my comment, you know that VersionInfo is null. The call to Trim() is failing because that will execute before the check if it equals String.Empty.

You should use (string.IsNullOrEmpty(VersionInfo) || VersionInfo.Trim().Length < 1) instead (or string.IsNullOrWhiteSpace(VersionInfo) if you're in .NET 4).

EDIT:

After seeing your response to another answer that you removed Trim() and it still doesn't work...at that point, it's the Equals call that will break. Try the code mentioned above and it should work fine.

于 2012-04-13T19:57:38.903 回答