代码之家  ›  专栏  ›  技术社区  ›  oliver

用于用户界面的字段的替代名称

c#
  •  0
  • oliver  · 技术社区  · 6 年前

    我想给一个字段(或属性)一个可以通过反射在用户界面中显示的替代名称。我找到了属性 DescriptionAttribute ,但这真的是为了这个目的还是我最好用别的东西?

    这个属性是否以某种方式限制在windows窗体及其属性视图中,还是独立于ui框架?(目前我正在为这个项目使用windows窗体,但将来可能会有所改变,所以我不想被它困住)

    public class MyCustomZoo
    {
        [Description("Cute Mouse")] 
        public MyCustomAnimal CuteMouse;
    
        [Description("Frightning Lion")] 
        public MyCustomAnimal FrightningLion;
    }
    
    0 回复  |  直到 6 年前
        1
  •  -1
  •   oliver    6 年前

    我在其中一个答案中找到了我的首选解决方案 here .

    using System.ComponentModel.DataAnnotations;
    
    // ...
    
    public class MyCustomZoo
    {
        [Display(Name = "Cute Mouse")] 
        public object CuteMouse;
    
        [Display(Name = "Frightning Lion")] 
        public int FrightningLion;
    }   
    
    public static string FieldDisplayName(FieldInfo field)
    {
        DisplayAttribute da = (DisplayAttribute)(field.GetCustomAttributes(typeof(DisplayAttribute), false)[0]);
        return da.Name;
    }
    
    // ...
    
    // c# identifier names, results in {"CuteMouse","FrightningLion"}   
    List<string> fieldNames = typeof(MyCustomZoo).GetFields().Select(field => field.Name).ToList();
    
    // "human readable" names, results in {"Cute Mouse","Frightning Lion"}  
    List<string> fieldDisplayNames = typeof(MyCustomZoo).GetFields().Select(field => FieldDisplayName(field)).ToList();
    

    不要忘记添加对程序集的引用 System.ComponentModel.DataAnnotations .

    注: 如果要标记的是属性,那么还可以使用system.componentmodel.displaynameattribute(感谢kieran devlin)。但是对于纯场,它不起作用。