在对象不会抛出异常的方法调用 [英] Method call on object does NOT throw exception
问题描述
这几天我遇到的many奇怪的场景的: - )
我已经测试了以下两个codeS在ASP.Net应用程序。 code 1抛出异常(如预期),而code 2不抛出异常(意料之外)当字符串值为空。
- 为什么 EVAL ,在这种情况下,没有引发异常?
- 威尔EVAL工作总是这样(即无异常),或者是它只是一个运气?
- 有没有参考MSDN,上面写着评估和演示的回报空字符串?
// code 1 :导致异常
字符串测试= Convert.ToString(subscriber.EncryptedSSN).Substring(0,Convert.ToString(subscriber.EncryptedSSN)。长度> = 5:Convert.ToString(用户.EncryptedSSN)。长度);
// code 2 :不抛出异常。
<%#Convert.ToString(EVAL(EncryptedSSN))子字符串(0,Convert.ToString(EVAL(EncryptedSSN))长方式> = 5? 5:Convert.ToString(EVAL(EncryptedSSN))的长度)%方式>
参考
您的情况似乎是不正确的。第一个.NET 4不给为我破例:
对象foo = NULL;字符串测试= Convert.ToString(富).Substring(0,Convert.ToString(富)。长度> = 5:Convert.ToString(富)。长度);
这是因为 Convert.ToString()
的返回重价值presentation,或的String.Empty字符串如果值为null的。
的String.Empty不为空,它是一个长度为0的字符串,所以它不会抛出一个异常,当调用一个方法就可以了。
搜索的一点使我此页面,解释数据绑定在ASP中一般,并解释说,的在运行时,Eval方法调用DataBinder的对象的Eval方法的。 的DataBinder.Eval()
返回一个对象,那么 Convert.ToString(EVAL(东西))
至少会返回的String.Empty
如果您尝试访问它的结果的成员或属性,因此不抛出一个NullReferenceException。
These days I am running into many strange scenarios :-)
I have tested the following two codes in ASP.Net application. Code 1 throws exception (as expected) whereas Code 2 does not throw exception (contrary to expectation) when the string value is null.
- Why is "EVAL" not throwing exception in this case?
- Will EVAL work always like this (i.e., "no exception") or is it just a luck?
- Is there any MSDN reference that says 'Eval' returns empty string?
//Code 1: Causes Exception
string test = Convert.ToString(subscriber.EncryptedSSN).Substring(0, Convert.ToString(subscriber.EncryptedSSN).Length >= 5 ? 5 : Convert.ToString(subscriber.EncryptedSSN).Length);
// Code 2: Does not throw Exception
<%# Convert.ToString(Eval("EncryptedSSN")).Substring(0, Convert.ToString(Eval("EncryptedSSN")).Length >= 5 ? 5 : Convert.ToString(Eval("EncryptedSSN")).Length) %>
References:
- Eval check for DBNull doesnt work
- Convert.ToString behaves differently for "NULL object" and "NULL string"
- Datatype returned varies based on data in table
Your scenario appears to be incorrect. The first does not give an exception for me on .NET 4:
object foo = null;
string test = Convert.ToString(foo).Substring(0, Convert.ToString(foo).Length >= 5 ? 5 : Convert.ToString(foo).Length);
This is because Convert.ToString()
returns "The string representation of value, or String.Empty if value is null".
String.Empty is not null, it is a string of length 0, so it will not throw an exception when a method is called on it.
A bit of searching led me to this page, explaining databinding in ASP in general, and it explains that "At run time, the Eval method calls the Eval method of the DataBinder object". DataBinder.Eval()
returns an object, so Convert.ToString(Eval(Something))
will at least return String.Empty
, thus not throwing a NullReferenceException if you try to access its result's members or properties.
这篇关于在对象不会抛出异常的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!