如何以通用方式写下面的逻辑?

我有一个如下的模型

public sealed class Person { public string MobileNo { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } } 

在我的implmentation类中,我有一个方法,它将IEnumerable作为参数

 public string PersonList(string listName, IEnumerable persons) { dictionary.Add("name", new String[1] { listname }); dictionary.Add("list", persons.ToArray()); PrivateMethod("personList", dictionary); } 

我有另一种私人方法

 private string PrivateMethod(string value, Dictionary parameters) { foreach (KeyValuePair kvp in parameters) { Person[] persons = kvp.Value.Cast().ToArray(); [...] } [...] } 

我想让上面这个方法可以重用,并且不想把“Person”模型紧密耦合。

我可以使用动态吗?

 ContactList(string listName, IEnumerable persons) 

并在私人方法内

dynamic[] persons = kvp.Value.Cast< 如何在这里传递模型 >().ToArray();

解:

这很有用。

  dynamic[] persons = kvp.Value.Cast().ToArray(); 

感谢usrRune FS

您是否尝试在c#中使用“接口”? 您可以将任何对象转换为任何类型,只要它们都派生到相同类型的接口即可。

 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 dictionary = new Dictionary(); public void run() { List persons = new List(); 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 persons) { //dictionary.Add("name", new String[1] { listName }); dictionary.Add("list", persons.ToArray()); return PrivateMethod("personList", dictionary); } private string PrivateMethod(string value, Dictionary parameters) { foreach (KeyValuePair kvp in parameters) { IPerson[] persons = kvp.Value.Cast().ToArray(); } return "somestring"; } 

你可以使PrivateMethod通用:

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