我有一个类似下面的模型
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<Person> persons)
{
dictionary.Add("name", new String[1] { listname });
dictionary.Add("list", persons.ToArray());
PrivateMethod("personList", dictionary);
}
我有另一种私人方法
private string PrivateMethod(string value, Dictionary<string, object[]> parameters)
{
foreach (KeyValuePair<string, object[]> kvp in parameters)
{
Person[] persons = kvp.Value.Cast<Person>().ToArray();
[...]
}
[...]
}
我想让上面的方法可重用,并且不希望将“Person”模型紧密耦合。
我可以使用动态吗?
ContactList(string listName, IEnumerable<dynamic> persons)
在私人方法中
dynamic[] persons = kvp.Value.Cast<
如何在此处传递模型 >().ToArray();
解决方案:
这很有效。
dynamic[] persons = kvp.Value.Cast<dynamic>().ToArray();
感谢 usr &amp; 符文FS
答案 0 :(得分:4)
您可以制作PrivateMethod
通用:
private string PrivateMethod<T>(string value, Dictionary<string, object[]> parameters)
{
foreach (KeyValuePair<string, object[]> kvp in parameters)
{
T[] items = kvp.Value.Cast<T>().ToArray();
[...]
}
[...]
}
答案 1 :(得分:0)
您是否尝试在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<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";
}