Объединил верхние ответы для создания анонимной версии объекта:
var queryString = HttpUtility2.BuildQueryString(new
{
key2 = "value2",
key1 = "value1",
});
Это генерирует это:
key2 = value2 & amp; key1 = value1
blockquote> blockquote>Вот код:
public static class HttpUtility2 { public static string BuildQueryString<T>(T obj) { var queryString = HttpUtility.ParseQueryString(string.Empty); foreach (var property in TypeDescriptor.GetProperties(typeof(T)).Cast<PropertyDescriptor>()) { var value = (property.GetValue(obj) ?? "").ToString(); queryString.Add(property.Name, value); } return queryString.ToString(); } }