简体   繁体   中英

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

Let me list all of my current classes and interfaces:

IItem:

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

Item:

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

    T Data => data;
}

Equipment:

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

How can I get Data using IEquipment? Thanks.

You can't directly, you need some cast first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM