如何写下面的逻辑通用的方式? [英] How to write below logic in Generic way?
本文介绍了如何写下面的逻辑通用的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面的模型
public sealed class Person
{
public string MobileNo { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
在我implmentation课,我有一个方法,需要一个的IEnumerable
作为一个参数
In my implmentation class, I have a method which takes an IEnumerable
as a parameter
public string PersonList(string listName, IEnumerable<Person> persons)
{
dictionary.Add("name", new String[1] { listname });
dictionary.Add("list", persons.ToArray());
PrivateMethod("personList", dictionary);
}
我还有一个私有方法
I have another private method
private string PrivateMethod(string value, Dictionary<string, object[]> parameters)
{
foreach (KeyValuePair<string, object[]> kvp in parameters)
{
Person[] persons = kvp.Value.Cast<Person>().ToArray();
[...]
}
[...]
}
我想使这个上面的方法可重复使用,并且不希望把人模型紧耦合。
我可以使用动态
ContactList(string listName, IEnumerable<dynamic> persons)
和私有方法在
动态[]人= kvp.Value.Cast&LT;
如何在这里通过模型 &GT;()。的ToArray();
解决方法:
这将工作,非常棒。
dynamic[] persons = kvp.Value.Cast<dynamic>().ToArray();
由于 USR &放大器; 符文FS
推荐答案
您是否尝试过在C#中使用接口?你可以将任何对象的任何类型的,只要它们都来自相同类型的接口。
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";
}
这篇关于如何写下面的逻辑通用的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文