Is there are way to combine "is" and "as" in C# [duplicate]
Po开发者_运维问答ssible Duplicate:
C# - Assignment in an if statement
I find my myself doing the following multiple time
if (e.row.FindControl("myLiteral") is Literal)
{
(e.row.FindControl("myLiteral") as Literal).Text = "textData";
}
Is there way to replace the "if" part and simplify the setter:
(e.row.FindControl("myLiteral") <some operator that combines is and as> .text = "textData";
EDIT: I should have mentioned this before- I want to remove the 'if' entirely.
"some operator " should do this internally and set the ".text" only if e.row.FindControl is a literalNormally I wouldn't combine them like that to start with - I'd either use a cast or I'd use as
and a null check:
Literal literal = e.row.FindControl("myLiteral") as Literal;
if (literal != null)
{
literal.Text = "textData";
}
There is no built-in way to do this. However you could author an extension method which gives you this capability
public static void AsType<T>(object o, Action<T> action) where T : class
{
var value = o as T;
if (value != null)
{
action(value);
}
}
You could then write
e.row.FindControl("myLiteral").AsType<Literal>(l => l.Text = "textData");
the as operator already does an is. If the cast succeed it returns the casted value, otherwise it returns null.
Literal lit = e.row.FindControl("myLiteral") as Literal;
if (lit != null)
{
lit.Text = "textData";
}
or
if (e.row.FindControl("myLiteral") is Literal)
{
Literal lit = (Literal)e.row.FindControl("myLiteral");
lit.Text = "textData";
}
A check using is
is typically followed by a cast:
if (e.row.FindControl("myLiteral") is Literal)
{
((Literal)e.row.FindControl("myLiteral")).Text = "textData";
}
Whereas as
functions as such a check that returns either a successfully cast instance or null
to the assigned variable, which you can then check for null
(See @Jon Skeet's answer).
You could do:
var literal = e.row.FindControl("myLiteral") as Literal;
if (literal != null)
{
literal.Text = "textData";
}
Well, you could use as
more like this (the standard usage):
Literal lit = e.row.FindControl("myLiteral") as Literal;
if (lit != null) {
lit.Text = "textData";
}
If you're using .Net 3.5 or greater you could create an extension method to handle this (kind of):
internal static class Extensions {
internal static void SetTextLiteral(this Control c, string text) {
Literal lit = c as Literal;
if (lit != null)
lit.Text = text;
}
}
void Sample() {
e.row.FindControl("myLiteral").SetTextLiteral("textData");
}
精彩评论