Use of an Interface and a ListT

0

If I have an Interface that I later implement in a class, when I implement it in a List, can T be the name of the interface?

Interface:

interface IItem
{
    int id { get; set; }
    string name { get; set; }
}

Serialized class:

[System.Seriazable]
public class Martillo : IItem
{
    public int damage { get; set; }

    // Implement interface  IItem
    int id { get; set; }
    string name { get; set; }
}    

Dictionary method:

public Dictionary<string, List<T> addDictionary<T>( T _item, string _index){

     Dictionary<string, List<T> dic = new Dictionary<string, List<T>();    
     dic.Add(_index, List<_item>);

     return dic;

}

The case in point is that I have a Dictionary that houses a list, when I want to extract the list from the dictionary it becomes an object and it does not let me use the methods of List < & gt ;. I can castear the object that returns to me from its interface (already in this dictionary I have several list of with the same interface).

Can I cast him like that?

List<IItem> martillo = dictionary["Martillo"] as List<IItem>;

Or do I have to do it by force like this?

List<Martillo> martillo = dictionary["Martillo"] as List<Martillo>;
    
asked by dGame 04.09.2017 в 15:53
source

1 answer

0

First of all, your code does not compile. You are missing some > at the end of the types and in the case of Add I guess the item you spend you want to wrap it in a list. Making those changes should be like this

public Dictionary<string, List<T>> addDictionary<T>(T _item, string _index)
{
    Dictionary<string, List<T>> dic = new Dictionary<string, List<T>>();
    dic.Add(_index, new List<T>(){ _item });
    return dic;
}

Now if given that code you could do for example

var dic = addDictionary(martillo, "Martillo");
var listMartillo = dic["Martillo"]; // la variable listMartillo es de tipo List<Martillo> y contiene un elemento.

Second, if that dictionary is only going to contain Lists of Item I recommend that you put a constraint that tells just this to the method: where T: IItem

public Dictionary<string, List<T>> addDictionary<T>(T _item, string _index) where T : IItem
{
    Dictionary<string, List<T>> dic = new Dictionary<string, List<T>>();
    dic.Add(_index, new List<T>(){ _item });
    return dic;
}
    
answered by 04.09.2017 в 16:07