例如:
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;
关于c# - 如何更改类/属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395379/