所以我在查看旧代码 (2.0) 时遇到了这个:
object isReviewingValue = ViewState["IsReviewing"];
if (isReviewingValue is bool)
{
return (bool)isReviewingValue;
}
我的第一个想法是我们使用“as”关键字来避免不必要的
(bool)isReviewingValue;
但是“as”只适用于非值类型。没问题,我只是继续这样做:
bool? isReviewingValue= ViewState["IsReviewing"] as bool?;
if (isReviewingValue.HasValue)
{
return isReviewingValue.Value;
}
问题是:除了看起来更具可读性之外,这实际上更好吗?
编辑:
public Stopwatch AsRun()
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
{
Object value = true;
Boolean? test = value as Boolean?;
if (test.HasValue)
{
Boolean something = test.Value;
}
}
watch.Stop();
return watch;
}
public Stopwatch ObjectIsRun()
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
{
Object test = true;
if (test is Boolean)
{
Boolean something = (Boolean)test;
}
}
watch.Stop();
return watch;
}
答案:事实证明,使用上述方法以测试方式运行,原始代码的速度大约快 10 倍。
最佳答案
合并运算符将为您删除一些代码。要回答您的问题,正如 Jimmy 所说的那样,两者之间的技术差异很小,因此请使用您认为更好的那个。我个人倾向于使用这种方法。 我可能会被认为有偏见......
private bool GetIsReviewing()
{
return (ViewState["IsReviewing"] as bool?) ?? false;
}
关于c# - 使用 "as bool?"而不是 "object something = ViewState["hi"]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2675537/