例如:
public class Car{
public string color {get; set;}
public int VINCode {get;set;}
}
现在,如果我呼叫
nameof(Car)
,它将返回“ Car”[Name("something")]
public class Car{
[Name("something_else")]
public string color {get; set;}
public int VINCode {get;set;}
}
但是如何获取nameof以返回Name属性中的值,而不是类或方法的名称。例如:
nameof(Car) == "something"
或nameof(Car.color) == "something_else"
。问题:
var modelState = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(data);
var departmentViewModels = modelState[nameof(DepartmentListView.DepartmentsViewModels)][0];
var departmentTypes = modelState[nameof(DepartmentListView.DepartmentsViewModels)][0];
为此修复:
var modelState = JsonConvert.DeserializeObject<DepartmentListView>(data);
var departmentViewModels = modelState.DepartmentsViewModels;
var departmentTypes = modelState.DepartmentTypes;
此序列化:
public class DepartmentListView
{
public IEnumerable<DepartmentViewModel> DepartmentsViewModels { get; set; }
public IEnumerable<DepartmentType> DepartmentTypes { get; set; }
}
将会:
departmentsViewModel : [], departmentTypes : [] (with lowercase)
我知道我可以使用JsonProperty更改小写序列化,但是我认为我可以更改类或属性的名称...
最佳答案
恐怕您不能使用nameof
来做到这一点。
但是,如果要获取CustomAttribute
的值,可以尝试以下操作:
// I assume this is your Name class
public class Name: Attribute
{
public string Data { get; }
public Name(string data) { Data = data; }
}
那么你也能
// Will return "something"
var classAttrData = ((Name) typeof(Car).GetCustomAttribute(typeof(Name))).Data;
// Will return "something_else"
var fieldAttrData = ((Name) typeof(Car).GetField(nameof(Car.color)).GetCustomAttribute(typeof(Name))).Data;