简体   繁体   English

创建通用IList <T> 方法

[英]Create Generic IList<T> method

Is it possible to create a generic IList method? 是否可以创建通用的IList方法? Here's how I want it to be implemented: 这是我希望其实现的方式:

List<Entity1> lstEnt1 = _myClass.GenerateListFromXml<Entity1>(@"C\test.xml");
List<Entity2> lstEnt2 = _myClass.GenerateListFromXml<Entity1>(@"C\test.xml");

Here's what I got so far: 这是到目前为止我得到的:

    public List<XMLModule> RetrieveListFromXml(string appSetting, string module)
    {
        throw new NotImplementedException();
    }

I want to change the XMLModule to a generic one which I can pass in an entity. 我想将XMLModule更改为可以在实体中传递的通用模型。

Need help on this guys. 需要帮助的家伙。 Thanks! 谢谢!

public List<T> RetrieveListFromXml<T>(string appSetting, string module)
{
    throw new NotImplementedException();
}

Pretty simple, just use a generic T type and then decide the internal behavior. 非常简单,只需使用泛型T类型,然后确定内部行为即可。

public List<T> RetrieveListFromXml<T>(string appSetting, string module)
{
    throw new NotImplementedException();
}

You could use something like this (I ignored your appSetting/module parameters and went based on your XML file paths used at the top) 您可以使用类似的方法(我忽略了appSetting / module参数,并根据顶部使用的XML文件路径进行了操作)

    public static List<T> RetrieveListFromXml<T>(string xmlFilePath)
    {
        var serializer = new XmlSerializer(typeof(List<T>));
        object result;
        using (var stream = new FileStream(xmlFilePath, FileMode.Open))
        {
            result = serializer.Deserialize(new FileStream(xmlFilePath, FileMode.Open));
        }
        return (List<T>)result;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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