【发布时间】:2017-02-22 15:14:36
【问题描述】:
例如:
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是专门为使用类、变量等的当前名称而设计的。其目的是如果更改名称,程序员就不必更改硬编码的文字文本无处不在。 -
同意,这个问题感觉有点奇怪,也许如果你解释一下你最终想要完成的事情,也许有一个更实际的方法来实现它。
-
这似乎是一个经典的XY Problem 场景
-
您的编辑并没有让事情变得更加清晰。我无法通过仅显示一大段代码来理解“问题”是什么。同样,当它只是另一块代码时,“修复”甚至意味着什么还不清楚。我建议您阅读此处已链接的一些资源以及有关 minimal reproducible example 的资源。
标签: c# custom-attributes nameof