[英]Convert a list to a object c#
I have a common method which accepts any paramater as object 我有一个通用的方法可以接受任何参数作为对象
public static object Populate(object anyStuff)
{
}
I to send a List of a user defined class to this. 我向它发送用户定义类的列表。 and then de serialize it again in the method to loop through it.
然后在方法中再次对其进行反序列化以遍历它。 I am not sure how to accomplish.
我不确定如何完成。
You can use Generics . 您可以使用泛型 。
Where you can create the generic method that handles different type of list and operates on them: 您可以在其中创建用于处理不同类型的列表并对其进行操作的通用方法:
public static T Populate<T>(List<T> list){
//Do stuff
}
But if you are using talking about object (do note, not a good way you are trying to achieve): 但是,如果您使用的是谈论对象(请注意,这不是您尝试实现的好方法):
public static object Populate(object anyStuff){
//Explicit typecast
List<string> value = anyStuff as List<string>();
}
If you want to know the usage of the first example with generic, here you can see the example 如果您想了解第一个示例与泛型的用法,请在此处查看示例
Usually you would create multiple overloads of Populate. 通常,您会创建多个Populate重载。
If I read your question correctly, you'd like something like this: 如果我正确阅读了您的问题,则您需要执行以下操作:
var properties = new Dictionary<string, object>
{
{"Name", "Bart"},
{"Date", new DateTime(2014,9,23)},
{"Age", 300}
}
var item = HelperClass.Populate(properies)
Console.WriteLine(item.Name); // should print "bart"
If this is what you want, you should look into the dynamic ExpandoObject. 如果这是您想要的,则应查看动态ExpandoObject。 (see http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html )
(请参阅http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html )
public static dynamic Populate(IDictionary<string, object> anystuff)
{
IDictionary<string, object> expando = new ExpandoObject()
foreach(var key in anystuff)
{
expando[key] = anystuff[key];
}
return expando;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.