在我的代码中,我在 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
, 你可以测试 int
与 Values["id"] is int
. Values[]
属性类型为对象。因此它可以是null
.但这并不意味着存储的 int
是 Nullable<int>
. (请参阅下面我的更新。)
如果您分配 int
(以及所有其他非引用类型)对象变量或属性,它将被装箱。 IE。它将被打包到相应类型的对象中。 int
或 System.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 int
和 obj is int?
返回 true
如果obj
包含 int
数字,但如果 obj
都返回 false包含 null
! null
Nullable<int>
转换为 (object)null
当分配给 obj
不再是Nullable<int>
.
调试器显示 obj
的类型作为object {int}
当有数字存储时,无论是否 int
或 int?
被分配了! obj
的类型是object
什么时候null
已存储。
所以 Chuong Le 其实是对的!
关于c# - 使用 "as"运算符测试 Page.RouteData.Values 中的整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12711082/