簡體   English   中英

如何使用其他非通用接口訪問通用接口的屬性

[英]How to reach a property of a generic interface with other non-generic interface

讓我列出我當前所有的類和接口:

項目:

public interface IItem<T> where T : ItemData {
    T Data { get; }
}

物品:

public class Item<T> : IItem<T> where T : ItemData {
    T data = null; // I am setting this something else later on

    T Data => data;
}

設備:

public class Equipment<T> : Item<T>, IEquipment where T : EquipmentData {
    // Code...
}

如何使用 IEquipment 獲取數據? 謝謝。

你不能直接,你需要先進行一些轉換。

IEquipment equipement = new Equipment();

// ...

// 'object as type' will cast the object with the corresponding type if possible, else return null
var data = (equipement as ItemData)?.Data; // data will be null if cast is not possible

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM