如何更改类/属性名称?

时间:2017-02-22 15:14:36

标签: c# custom-attributes nameof

例如:

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 更改小写序列化,但我认为我可以更改类或属性的名称......

2 个答案:

答案 0 :(得分:3)

我担心你不能用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;

答案 1 :(得分:0)

看起来您是在询问您尝试的解决方案,而不是您的实际问题。

获取类/属性的新名称的解决方案:

使用 DisplayNameAttribute 创建您的类,如下所示:

[DisplayName("something")]
public class Car
{
    [DisplayName("something_else")]
    public string color { get; set; }

    public int VINCode { get; set; }
}

要获取您的类属性名称:

var attributes = typeof(Car) // type declaration
        
        .CustomAttributes.FirstOrDefault() // first item of collection that contains this member's custom attributes like [DisplayName("something")]
        
        ?.ConstructorArguments.FirstOrDefault() // first item of structure collecion
        
        .Value; // value as string - "something"

和属性名类似,只需要先获取它的类型

var attribute = typeof(Car).GetProperty(nameof(Car.color)) // ...

代替

var attribute = typeof(Car) // ...