[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
is检查一个对象是否兼容于指定的类型,返回Boolean值。注意is操作符永远不会抛异常。is操作符通常这样使用:
if(o is Employee) { Employee e=(Employee) 0; //其他处理... }
在这段代码中,CLR实际会检查两次对象类型。is操作符首先核实o是否兼容于Employee类型。如果是,将在if语句内部再次核实o是否引用一个Employee。CLR的类型检查增强了安全性,但无疑也对性能造成一定影响。这是因为CLR首先必须判断变量(o)引用的对象的实际类型。然后,CLR必须遍历继承层次结构用每一个基类型去核对指定的类型。这是一个相当常用的编程模式,所以C#专门提供了as操作符,目的简化这种代码的写法,同时提升其性能。
Employee e=o as Employee; if(e!=null) { //后续其他处理 }
在这段代码中,CLR核实o是否兼容于Employee类型;如果是,as会返回对同一个对象的一个非null引用。如果不兼容,返回null。as操作符造成CLR只校验一次对象的类型。if语句只是检查e是否为null。这个检查速度比校验对象的类型快得多。
实际中其实可以这么写:
public class Program { static void Main(string[] args) { Object o = new
Test(); if (o is Test test) { var a = test.Age; } Console.ReadKey(); } } public
class Test { public int Age }
反编译后发现:原本写的是is,反编译后代码是as。并且会自动判断能否装换成功,能成功,则返回转换后的对象赋给test。