在程序中有时候回遇到需要把实体Model转化成url参数的格式,去请求某个接口
现在有一个实体
public class Model
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public string D { get; set; }
}
现在需要的参数格式是 A=3&B=3&C=3这种格式
/// <summary>
/// 参数拼接Url
/// </summary>
/// <param name="source">要拼接的实体</param>
/// <paramref name="IsStrUpper">是否开启首字母大写,默认小写</paramref>
/// <returns>Url,</returns>
public static string ToPaeameter(this object source, bool IsStrUpper = false)
{
var buff = new StringBuilder(string.Empty);
if (source == null)
throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (value != null)
{
if (IsStrUpper)
{
buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
}
else
{
buff.Append(WebUtility.UrlEncode(GetlowerStr(property.Name)) + "=" + WebUtility.UrlEncode(value + "") + "&");
}
}
}
return buff.ToString().Trim('&');
}
/// <summary>
/// 让首字母小写
/// </summary>
/// <param name="proname">类属性名称</param>
/// <returns></returns>
private static string GetlowerStr(object proname)
{
if (proname.ToString().Length >= 1)
{
return string.Format("{0}{1}", proname.ToString().Substring(0, 1).ToLower(), proname.ToString().Substring(1));
}
return string.Empty;
}
现在我们来调用一下这个方法
static void Main(string[] args)
{
var Moel = new Model() { A=3,B=3,C=3};
//var res = Moel.ToPaeameter();
var res = Moel.ToPaeameter();
Console.WriteLine(res);
Console.ReadKey();
}
结果