@ndrew ([info]andrew_molyuk) wrote in [info]code_wtf,
@ 2008-06-12 19:20:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
Отображение ошибок...
catch (Exception ex)
{
lblError.Text = "An error occurred performing the operation: " + ex.Message;
Label mainErrorLabel = (Label)
this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.FindControl("lblError");
if (mainErrorLabel != null)
mainErrorLabel.Text = lblError.Text;
...



(Post a new comment)


[info]darkdeny
2008-06-12 05:49 pm UTC (link)
Жесть....

(Reply to this)


[info]einri
2008-06-12 06:05 pm UTC (link)
шикарно

(Reply to this)


[info]b0rg
2008-06-12 06:16 pm UTC (link)
Ну хоть без рефлекшена и на том спасибо...

(Reply to this)


[info]green_serpent
2008-06-12 06:42 pm UTC (link)
а зачем проверка на null?
Если Label не найдется, то оно ж само упадет на приведении.

(Reply to this)(Thread)


[info]andrew_molyuk
2008-06-12 07:26 pm UTC (link)
Да ну?... не упадет - переменнная mainErrorLabel получит значение null... и все... А потому предусмотрительный гений с предосторожностями проверяет значение на null... Как бы чего не упало... вдруг...

(Reply to this)(Parent)(Thread)


[info]green_serpent
2008-06-12 07:30 pm UTC (link)
лично я привык пользовать "as". Оно честнее.

(Reply to this)(Parent)


[info]andrew_molyuk
2008-06-12 07:28 pm UTC (link)
Дополнение - это C#... Хотя, я думаю, что это и так заметно... :)

(Reply to this)(Parent)(Thread)


[info]aensidhe
2008-06-12 08:48 pm UTC (link)
в C# null получится в таком коде не может.

Будет либо не Null, либо InvalidCastException.

(Reply to this)(Parent)(Thread)


[info]andrew_molyuk
2008-06-12 09:19 pm UTC (link)
При исполнении следующего кода:

Label l = (Label)FindControl("undefined");

не произойдет никаких исключений, если данный контрол не существует... Обратимся к первоисточнику...

Первый источник:
http://msdn.microsoft.com/en-us/library/486wc64h.aspx
Цитата:
Return Value
Type: System.Web.UI..::.Control
The specified control, or nullNothingnullptra null reference (Nothing in Visual Basic) if the specified control does not exist.

Другой источник:
http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx
Другая цитата:
InvalidCastException is thrown if:
For a conversion from a Single or a Double to a Decimal, the source value is infinity, Not-a-Number (NaN), or too large to be represented as the destination type.
A failure occurs during an explicit reference conversion.

(Reply to this)(Parent)(Thread)


[info]aensidhe
2008-06-12 09:21 pm UTC (link)
TextBox t = new TextBox();
Label l = (Label) t;

Запустите, посмотрите.

(Reply to this)(Parent)(Thread)


[info]tonybelol
2008-06-12 09:24 pm UTC (link)
Если приводить _разные_ контроли, то ошибка каста вылезет, а если контроль просто не нашли, то будет null без ошибок:

http://community.livejournal.com/code_wtf/134435.html?thread=2052387#t2052387

(Reply to this)(Parent)(Thread)


[info]aensidhe
2008-06-12 09:25 pm UTC (link)
ну да, про null из функции я забыл.

просто где гарантия, что там будет именно Label? :)

(Reply to this)(Parent)(Thread)


[info]andrew_molyuk
2008-06-12 09:28 pm UTC (link)
Гарантий никаких... Так писать, скажем, не полезно для здоровья... Как читающего код, так и, как последствия первого, пишущего его... :)

(Reply to this)(Parent)


[info]tonybelol
2008-06-13 01:19 pm UTC (link)
Гарантий, конечно, никаких, но я думаю, что вероятность того, что найденый контрол будет Лейблом выше, чем вероятность того, что this.Parent.Parent.Parent.Parent.Parent.Parent.Parent вообще вернет что-нибудь при поиске.

(Reply to this)(Parent)


[info]andrew_molyuk
2008-06-12 09:26 pm UTC (link)
В данном случае Вы абсолютно правы - reference существует и произойдет исключение.

(Reply to this)(Parent)

Новости
[info]tonybelol
2008-06-12 09:22 pm UTC (link)
Код asp.net 2.0:

<form id="form1" runat="server">
<asp:Label ID="lbl" runat="server" Text="test1">
</form>


code-behind:

protected void Page_Load(object sender, EventArgs e)
{
Label mainErrorLabel = (Label) FindControl("lblError");
lbl.Text = "mainErrorLabel is null: " + (mainErrorLabel == null);
}

Выхлоп:
mainErrorLabel is null: True

(Reply to this)(Parent)


[info]yosefk
2008-06-12 06:49 pm UTC (link)
"Parent... Parent... Parent..." - привычно отозвалось эхо.

(Reply to this)


[info]geniusua
2008-06-12 07:14 pm UTC (link)
красиво

(Reply to this)


[info]syarzhuk
2008-06-23 08:37 pm UTC (link)
>this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.FindControl
эта... папа... папа... папа... папа... папа... папа... папа... найди рычаг управления!

У меня когда-то сотрудник тоже обнаружил проблему - у него был пятиуровневый call stack, и тут он обнаружил, что на нижнем уровне ему нужно значение, известное на самом верхнем. С одной стороны, менять сигнатуры в пяти местах геморройно и может поломать чей-то ещё код. С другой, значение-то передать надо! Что сделал чувак? Правильно, обратился по имени (ColdFusion):

<cfset StructureThatINeedHere = evaluate("caller.caller.caller.caller.#attributes.StructureThatWasFiveLevelsUpAndWasNotPassedAsAParameter#")>

Хорошо, что я там больше не работаю

(Reply to this)



Create an Account
Forgot your login?
Login w/ OpenID
English • Español • Deutsch • Русский…