c# - 使用 "as"运算符测试 Page.RouteData.Values 中的整数类型

标签 c# .net

在我的代码中,我在 global.asax 中注册了如下路由:

void RegisterRoutes(RouteCollection routes)
{
   routes.MapPageRoute(
    "product",
    "product/{id}",
    "~/index.aspx"
);

然后在我的 index.aspx 页面中,我想测试 {id} 值是否为整数:

if (Page.RouteData.Values["id"] as int? != null)   
//always evaluate as null even id is an integer in the URL, ex: /product/1

我知道我可以使用一些其他方法(例如 int.TryParse 或 this )来实现相同的目标,但在这种情况下使用“as”有意义吗?

最佳答案

要走的路取决于真正存储在Values["id"] 中的内容.如果它实际上是一个 int , 你可以测试 intValues["id"] is int . Values[]属性类型为对象。因此它可以是null .但这并不意味着存储的 intNullable<int> . (请参阅下面我的更新。)

如果您分配 int (以及所有其他非引用类型)对象变量或属性,它将被装箱。 IE。它将被打包到相应类型的对象中。 intSystem.Int32作为值类型以及盒装和不可变的形式存在 System.Int32引用类型。由于它的不变性,您不会注意到它是一个引用类型。一个int可以用object obj = 5;装箱并用 int i = (int)obj; 拆箱.

另一方面,如果 id 存储为字符串,那么您必须将其转换为数字

int id;
if (Int32.TryParse((string)Page.RouteData.Values["id"], out id)) {
    // use id here
}

更新:

似乎与null有些混淆。和 Nullable<T> .

int? i; // Same as Nullable<int> or Nullable<System.Int32> or System.Int32?
object obj;
bool test;

i = null;
test = i.HasValue; // ==> false
test = i == null;  // ==> true

// Now comes the strange part

obj = 5;           // The int is boxed here.
// Debugger shows type of obj as "object {int}"
test = obj is int;   // ==> true
test = obj is int?;   // ==> true
int x = (int)obj;  // ==> 5, the int is unboxed here.

// But

obj = null;
// Debugger shows type of obj as "object"
test = obj is int; // ==> false
test = obj is int?; // ==> false
test = obj == null; // ==> true

// And
i = 5;
obj = i; // i is a Nullable<int>
// Debugger shows type of obj as "object {int}"
test = obj is int; // ==> true
test = obj is int?; // ==> true
test = obj == null; // ==> false

i = null;
obj = i;
// Debugger shows type of obj as "object"
test = obj is int; // ==> false
test = obj is int?; // ==> false
test = obj == null; // ==> true

两者都是 obj is intobj is int?返回 true如果obj包含 int数字,但如果 obj 都返回 false包含 null ! null Nullable<int>转换为 (object)null当分配给 obj不再是Nullable<int> .

调试器显示 obj 的类型作为object {int}当有数字存储时,无论是否 intint?被分配了! obj 的类型是object什么时候null已存储。

所以 Chuong Le 其实是对的!

关于c# - 使用 "as"运算符测试 Page.RouteData.Values 中的整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12711082/

相关文章:

c# - 如何在邮件中发送收件人的本地时间?

.net - 为什么.NET中没有SortedList <T>?

c# - 如果目标文件夹非常大,使用 System.Security.AccessControl 从文件夹 ACL 中删除 ACE 会非常慢

c# - 使用 http :\\URL 的 WPF 图像 UriSource 和数据绑定(bind)

c# - 有没有办法通过 VS 设计器严格将控件颜色设置为十六进制值?

.net - .NET 业务层中的结构与类

c# - 如何增加日期?

C# 正则表达式匹配,名称

c# - 是否有语句将元素 T 添加到 IEnumerable<T>

c# - C++ C# 委托(delegate)等效