繁体   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