Posted Dotnet9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了相关的知识,希望对你有一定的参考价值。
涓€锛氳儗鏅?/span>
1. 璁叉晠浜?span class="mq-7">
鏈€杩戝彂鐜?C#7 涔嬪悗鐨?is 鏄秺鏉ヨ秺鐪嬩笉鎳備簡锛屼箥涓€鐪嬭姳閲岃儭鍝ㄧ殑锛屼笉杩囧綋鎴戦潤涓嬪績鏉ヤ粩缁嗙爺璇伙紝鍙戠幇杩?is 鏄秺鏉ヨ秺鐭皬绮炬倣锛岃€屼笖杩樼壒鍒涔夊寲锛岄偅鎬庢槸涓€涓埥瀛椾簡寰楌煒勶紝杩欎竴绡囧氨鍜屽ぇ瀹剁畝鍗曡亰涓€鑱娿€?/p>
浜岋細C#7 涔嬪墠鐨?is 濡備綍浣跨敤
1. 绫诲瀷鍏煎鎬ф娴?span class="mq-15">
鐩镐俊瀛﹁繃 C# 鐨勬湅鍙嬮兘浼氱煡閬?is 鏄共鍢涚殑锛岃€屼笖杩樼粡甯稿拰 as 涓€璧锋瘮杈冿紝鍓嶈€呬竴鑸仛鍏煎鎬ф娴嬶紝鍚庤€呬竴鑸仛鍏煎鎬ц浆鎹紝杩欓噷鎴戝氨涓句釜渚嬪瓙鍚э細
static void Main(string[] args)
{
object slot = new Slot() { ClothesName = "涓婅。" };
if (slot is Slot)
{
Console.WriteLine($"slot is {nameof(Slot)}");
}
if (slot is IComparable)
{
Console.WriteLine($"slot is {nameof(IComparable)}");
}
}
public class Slot : IComparable
{
public string ClothesName { get; set; }
public int CompareTo(object obj) {return 0;}
}
浠庤繖涓緥瀛愬彲浠ョ湅鍒帮紝 object 绫诲瀷鐨?slot 鍜?Slot, IComparable 閮芥槸绫诲瀷鍏煎鐨勶紝闈炲父绠€鍗曘€?/p>
2. 閬楁喚鐨勫湴鏂?span class="mq-58">
鐒惰€屽湪瀹為檯缂栫爜涓紝鎴戠浉淇℃湁寰堝鏈嬪弸閮戒細鍦ㄥ悗缁殑杩囩▼涓敤鍒?slot 瀹炰緥锛岃€屼笂闈㈢殑杩欎釜渚嬪瓙锛屽嵆浣挎垜鐢?is 妫€娴嬪埌浜嗘槸 Slot 绫诲瀷锛屾渶鍚庢垜杩樻槸瑕?灏?object slot 寮鸿浆鎴?Slot绫诲瀷锛屽仛浜嗕竴娆℃娴嬶紝鍙堝仛浜嗕竴涓己杞紝杩欏氨寰堝钁╀簡锛屽涓嬩唬鐮侊細
if (slot is Slot)
{
var query = (Slot)slot;
Console.WriteLine($"slot is {nameof(Slot)}, ClothesName={query.ClothesName}");
}
闄ら潪鏈夋瘺鐥呮墠鍐欒繖鏍风殑浠g爜锛屽共鍢涗笉鐩存帴鐢?as 灏濊瘯鎬ц浆鎹㈠皢涓ゆ鍚堜负涓€姝ヨ蛋鍛紵淇敼浠g爜濡備笅锛?/p>
var query = slot as Slot;
if (query != null)
{
Console.WriteLine($"slot is {nameof(Slot)}, ClothesName={query.ClothesName}");
}
以上是关于的主要内容,如果未能解决你的问题,请参考以下文章