具有此数据:
class User
{
public string Name {get; set;}
public string SurrName {get; set;}
}
class Book
{
public int Id {get; set;}
public string Title {get; set;}
}
var user = getSampleUser();
var book = getSampleBook();
我想创建一个将序列化对象包含到&name=value
的字符串。
var userContent = user.ToRequestContent(); // "&Name=Adam&Surrname=Smith";
var bookContent = book.ToRequestContent(); // "&Id=5&Title=7";
我该怎么做?
答案 0 :(得分:3)
您可以尝试结合使用linq
来获取属性信息和值。
我会写一个扩展方法。
public static class ExtenstionArray
{
public static string ToRequestContent<T>(this T model) {
var list = model.GetType().GetProperties()
.Select(x => new
{
val = x.GetValue(model).ToString(),
name = x.Name
})
.Select(z => string.Join("=", z.name, z.val));
return "&"+ string.Join("&", list);
}
}
然后您可以像这样使用
。User u = new User() { Name = "test", SurrName = "aa" };
Book b = new Book() { Id = 134, Title = "aass" };
Console.WriteLine( u.ToRequestContent());
Console.WriteLine( b.ToRequestContent());
结果
&Name=test&SurrName=aa
&Id=134&Title=aass
答案 1 :(得分:0)
为什么不只是:
class User
{
public string Name {get; set;}
public string SurrName {get; set;}
public string ToRequestContent()
{
return "&Name="+Name+"&Surrname="+SurrName;
}
}
class Book
{
public int Id {get; set;}
public string Title {get; set;}
public string ToRequestContent()
{
return "&Id="+Id+"&Title="+Title;
}
}