To simplify the code
I confused: is there any way to simplify tha开发者_如何学JAVAt code?
private void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(pnlMain.Title) && string.IsNullOrWhiteSpace(Title))
pnlMain.Title = DefaultTitle;
else if (string.IsNullOrWhiteSpace(Title))
pnlMain.Title = DefaultTitle;
else
pnlMain.Title = Title;
}
If you draw up a logic table for it you should be able to work it out... Have columns for true and false for pnlMain.Title
being null or whitespace and rows for Title
being null or whitespace and then in each cell mark whether you use the DefaultTitle
or Title
when you go through the above logic.
You should get the result that it doesn't matter what pnlMain.Title is.
So that code is the same as:
if (string.IsNullOrWhiteSpace(Title))
pnlMain.Title = DefaultTitle;
else
pnlMain.Title = Title;
You can probably see it when you know the answer because in your code your first two checks are the same except with and without pnlMain.Title being checked as well and the same outcome.
From looking at what you might be trying to do you might in fact be wanting to do this:
if (string.IsNullOrWhiteSpace(pnlMain.Title))
{
if (string.IsNullOrWhiteSpace(Title))
pnlMain.Title = DefaultTitle;
else
pnlMain.Title = Title;
}
The above code will only change pnlMain.Title if it is null or white space and will use Title if that is not null or whitespace and otherwise fall back to DefaultTitle. This seems like more what I'd expect you to be wanting to do...
Looks like you can use ternary operator.
pnlMain.Title = (!string.IsNullOrWhiteSpace(Title))?Title:DefaultTitle;
You don't have to check string.IsNullOrWhiteSpace(pnlMain.Title)
because you are overwriting it anyway. But maybe it is another error in your code. So, what that piece of code meant to do?
Your else if (string.IsNullOrWhiteSpace(Title))
will always be true and the last else
will never be reached. You probably meant something like this:
if (string.IsNullOrWhiteSpace(pnlMain.Title))
pnlMain.Title = string.IsNullOrWhiteSpace(Title) ? DefaultTitle : Title;
This code is readable. Simplifying further, i.e. playing with ?:
, ||
, &&
, would lead to unreadable code. Hence it is simple just enough.
精彩评论