How to write below logic in Generic way?

拥有回忆 提交于 2019-12-05 19:53:36
masterlopau

Have you tried using "Interfaces" in c#? you can cast any object to any type as long as they are all derived to the same type of interface.

interface IPerson
{
    string MobileNo { get; set; }
    string Name { get; set; }
    string LastName { get; set; }
}

class Person : IPerson
{
    public string MobileNo { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
}

class execute
{
    private Dictionary<string, object[]> dictionary = new Dictionary<string,object[]>();

    public void run()
    {
        List<IPerson> persons = new List<IPerson>();
        persons.Add(new Person()
        {
            LastName = "asdf",
            Name = "asdf",
            MobileNo = "123123"
        });

        persons.Add(new Person()
        {
            LastName = "aaaa",
            Name = "dddd",
            MobileNo = "1231232"
        });

        string x = PersonList("somelistname", persons);
    }


    public string PersonList(string listName, IEnumerable<IPerson> persons)
    {
        //dictionary.Add("name", new String[1] { listName });
        dictionary.Add("list", persons.ToArray());

        return PrivateMethod("personList", dictionary);
    }

    private string PrivateMethod(string value, Dictionary<string, object[]> parameters)
    {
        foreach (KeyValuePair<string, object[]> kvp in parameters)
        {
            IPerson[] persons = kvp.Value.Cast<IPerson>().ToArray();

        }

        return "somestring";
    }

You could make the PrivateMethod generic:

private string PrivateMethod<T>(string value, Dictionary<string, object[]> parameters)
{
    foreach (KeyValuePair<string, object[]> kvp in parameters)
    {
           T[] items = kvp.Value.Cast<T>().ToArray();
           [...]
    }

    [...]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!