@Leigh Shepperson has the right idea; however, you can do it with less code using LINQ. I would create a helper method like this:
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
...
public static string GetFields(Type modelType)
{
return string.Join(",",
modelType.GetProperties()
.Select(p => p.GetCustomAttribute<JsonPropertyAttribute>())
.Select(jp => jp.PropertyName));
}
You can use it like this:
var fields = "&fields=" + GetFields(typeof(model));
EDIT
If you're running under the 3.5 version of the .Net Framework such that you don't have the generic GetCustomAttribute<T>
method available to you, you can do the same thing with the non-generic GetCustomAttributes()
method instead, using it with SelectMany
and Cast<T>
:
return string.Join(",",
modelType.GetProperties()
.SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute))
.Cast<JsonPropertyAttribute>())
.Select(jp => jp.PropertyName)
.ToArray());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…