我发现一篇文章对我遇到的问题提供了很好的答案,但我似乎找不到我正在寻找的小细节。
public class myModel
{
[JsonProperty(PropertyName = "id")]
public long ID { get; set; }
[JsonProperty(PropertyName = "some_string")]
public string SomeString {get; set;}
}
我需要一个返回的方法JsonProperty
PropertyName
的特定属性。也许我可以通过的东西Type
和Property
我需要,并且该方法返回值(如果找到)。
这是我发现的方法,它让我朝着正确的方向前进(我相信)取自这里
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>()
.Where(jp => jp != null)
.Select(jp => jp.PropertyName));
}
目标是调用这样的函数(任何修改都可以)
string field = GetField(myModel, myModel.ID);
更新#1
我将上面修改为这个,但我不知道如何获取字符串ID
from myModel.ID
.
public static string GetFields(Type modelType, string field) {
return string.Join(",",
modelType.GetProperties()
.Where(p => p.Name == field)
.Select(p => p.GetCustomAttribute<JsonPropertyAttribute>())
.Where(jp => jp != null)
.Select(jp => jp.PropertyName)
);
}
我想要prevent实际属性名称的硬编码字符串。例如我do not想要将上面的方法调用为:
string field = GetField(myModel, "ID");
我宁愿使用类似的东西
string field = GetField(myModel, myModel.ID.PropertyName);
但我不完全确定如何正确地做到这一点。
Thanks!