如果x == null,为什么x.ToString()会抛出错误? [英] Why does x.ToString() throw an error if x == null?

查看:123
本文介绍了如果x == null,为什么x.ToString()会抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有这样的东西


对象x = null;

MessageBox.Show(x.ToString())


我们收到错误。这种做法是有道理的,但没有理由

行为不能返回一个空字符串。当我们调用x.ToString时,我们

真正调用这样的函数:


class Object

{

public static string ToString(object * Instance)

{

//将对象指针转换为字符串的代码

}

}


为什么编译器只能将实例作为空传入并让代码排序

out out 。如果代码想要抛出一个错误,那么它可以但是如果它想要

做一些更有用的东西那么它可以。这在某些情况下会很有用(我承认它们很少见,但上面的ToString示例可能会被使用

)。我可以想到一些可能有用的情况,例如:


string x = null;

MessageBox.Show(x.IsNullOrEmpty.ToString( ))

MessageBox.Show(x.Length.ToString())//< ---显示零

DateTime? y;

MessageBox.Show(y.IsValid)


有趣的是你可以定义可以工作的扩展方法

null对象,例如


静态类扩展

{

public static bool IsSomething(this string s)

{

return!string.IsNullOrEmpty(s);

}

public static string ToStringIgnoreNull(this object s)

{

if(s == null)return string.Empty;

return s.ToString();

}

}


然后像这样使用:


string x = null;

if(x.IsSomething())MessageBox.Show(x)




object x = null;

MessageBox.Show(x.ToStringIgnoreNull())

有任何意见吗?


干杯,

Michael

If we have something like this

object x = null;
MessageBox.Show(x.ToString())

we get an error. That kindof makes sense but there is no reason the
behaviour couldn''t be to return an empty string. When we call x.ToString we
are really calling a function like this:

class Object
{
public static string ToString(object* Instance)
{
//code to convert the object pointer to a string
}
}

Why can''t the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:

string x = null;
MessageBox.Show(x.IsNullOrEmpty.ToString())
MessageBox.Show(x.Length.ToString()) //<--- shows zero
DateTime? y;
MessageBox.Show(y.IsValid)

The interesting thing is you can define extention methods that do work on
null objects, eg

static class Extensions
{
public static bool IsSomething(this string s)
{
return !string.IsNullOrEmpty(s);
}
public static string ToStringIgnoreNull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}

Then use it like this:

string x = null;
if (x.IsSomething()) MessageBox.Show(x)

or

object x = null;
MessageBox.Show(x.ToStringIgnoreNull())

Any comments?

Cheers,
Michael

推荐答案

" Michael C" < mi *** @ nospam.com写信息

新闻:u7 ************** @ TK2MSFTNGP03.phx.gbl ...
"Michael C" <mi***@nospam.comwrote in message
news:u7**************@TK2MSFTNGP03.phx.gbl...

[...]当我们调用x.ToString时,我们实际上正在调用这样的函数:


class Object

{

公共静态字符串ToString(对象*实例)

{
[...] When we call x.ToString we are really calling a function like this:

class Object
{
public static string ToString(object* Instance)
{



否,不真。你可以用扩展方法做到这一点(因为你已经在消息的末尾指出了
),但真正的ToString不是静态的;

它是一个虚方法可以在子类中重写:


class对象

{

公共虚拟字符串ToString()

{

返回this.GetType()。姓名;

}

}


如果对象为空,则无法工作。

No, not really. You can do that with extension methods (as you already
point out at the end of your message), but the real ToString is not static;
it is a virtual method that can be overridden in child classes:

class Object
{
public virtual string ToString()
{
return this.GetType().Name;
}
}

This can''t work if the object is null.


即使您声明了一个对象,它在您拥有之前并不存在

初始化它并且编译器没有为它留出任何空间。


要说,看看这个对象的空间我没有已创建并且

告诉我它的内容自然会抛出一个错误。


什么可能(虽然我不知道该怎么做)将是

定义你的行为编译器。如果x为null,那么编译器或

语言可以返回一些有用的东西(而不是崩溃或跑掉

到遗忘)。上帝知道我身上发生了很多事情!


" Michael C"写道:
Even if you declare an object, it doesn''t really exist yet until you have
initialized it and the compiler has not set aside any space for it.

To say, "Look at the space for this object that I have not created yet and
tell me what it says" would naturally throw an error.

What might be possible (though I wouldn''t know how to do it) would be to
define behaviors for your compiler. If x is null, then the compiler or
language could return something useful (instead of crashing or running off
into oblivion). God knows that happens to me plenty!

"Michael C" wrote:

如果我们有这样的东西


对象x = null;

MessageBox .Show(x.ToString())


我们收到错误。这种做法是有道理的,但没有理由

行为不能返回一个空字符串。当我们调用x.ToString时,我们

真正调用这样的函数:


class Object

{

public static string ToString(object * Instance)

{

//将对象指针转换为字符串的代码

}

}


为什么编译器只能将实例作为空传入并让代码排序

out out 。如果代码想要抛出一个错误,那么它可以但是如果它想要

做一些更有用的东西那么它可以。这在某些情况下会很有用(我承认它们很少见,但上面的ToString示例可能会被使用

)。我可以想到一些可能有用的情况,例如:


string x = null;

MessageBox.Show(x.IsNullOrEmpty.ToString( ))

MessageBox.Show(x.Length.ToString())//< ---显示零

DateTime? y;

MessageBox.Show(y.IsValid)


有趣的是你可以定义可以工作的扩展方法

null对象,例如


静态类扩展

{

public static bool IsSomething(this string s)

{

return!string.IsNullOrEmpty(s);

}

public static string ToStringIgnoreNull(this object s)

{

if(s == null)return string.Empty;

return s.ToString();

}

}


然后像这样使用:


string x = null;

if(x.IsSomething())MessageBox.Show(x)




object x = null;

MessageBox.Show(x.ToStringIgnoreNull())

有任何意见吗?


干杯,

Michael

If we have something like this

object x = null;
MessageBox.Show(x.ToString())

we get an error. That kindof makes sense but there is no reason the
behaviour couldn''t be to return an empty string. When we call x.ToString we
are really calling a function like this:

class Object
{
public static string ToString(object* Instance)
{
//code to convert the object pointer to a string
}
}

Why can''t the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:

string x = null;
MessageBox.Show(x.IsNullOrEmpty.ToString())
MessageBox.Show(x.Length.ToString()) //<--- shows zero
DateTime? y;
MessageBox.Show(y.IsValid)

The interesting thing is you can define extention methods that do work on
null objects, eg

static class Extensions
{
public static bool IsSomething(this string s)
{
return !string.IsNullOrEmpty(s);
}
public static string ToStringIgnoreNull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}

Then use it like this:

string x = null;
if (x.IsSomething()) MessageBox.Show(x)

or

object x = null;
MessageBox.Show(x.ToStringIgnoreNull())

Any comments?

Cheers,
Michael


" jp2msft" < jp ***** @ discussion.microsoft.com写信息

新闻:8D *********************** *********** @ microsof t.com ...
"jp2msft" <jp*****@discussions.microsoft.comwrote in message
news:8D**********************************@microsof t.com...

即使您声明了一个对象,它也不存在直到你有
初始化它并且编译器没有留出任何空间。
Even if you declare an object, it doesn''t really exist yet until you have
initialized it and the compiler has not set aside any space for it.



即使在声明对象之前,对象的大部分确实存在。

通常,实际代码将大于对象本身(大小)

并且所有代码都存在并准备好在实例创建之前调用


The bulk of the object does exist even before you declare the object.
Generally the actual code will be greater than the object itself (in size)
and all of the code exists and is ready to call before an instance is
created.


要说,看看我还没有创建的这个对象的空间和

告诉我它说的是什么自然会抛出一个错误。
To say, "Look at the space for this object that I have not created yet and
tell me what it says" would naturally throw an error.



没有理由在null对象上调用函数*有*引发

异常,C#的设计者只是设计了它那样。实际上他们需要额外支票才能阻止它工作。基本上当你打电话时,

说,object.ToString你最终调用了一个全局函数ToString,其中传递了

指向该对象的指针,即
< br $>
x.ToString();


转换为(当然在引擎盖下)


公共静态字符串ToString (对象* pObject)

{

//将pObject转换为sring

}


我我确定它比那更复杂,但这是基本的想法。

编译器在调用静态函数之前进行空检查但是

没有理由需要它。它可以轻松调用静态ToString

函数并让该函数决定是否允许空值。


Michael

There is no reason calling a function on a null object *has* to raise an
exception, the designers of C# just designed it that way. They actually
needed to put an extra check in to stop it working. Basically when you call,
say, object.ToString you end up calling a global function ToString where the
pointer to the object is passed in, ie

x.ToString();

translates to (under the hood of course)

public static string ToString(object* pObject)
{
//convert pObject to sring
}

I''m sure it''s more complicated than that but that''s the basic idea. The
compiler does the null check before the static function is called but there
is no reason that it needs to. It can easily call the static ToString
function and let that function decide whether to allow nulls or not.

Michael


这篇关于如果x == null,为什么x.ToString()会抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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