如何使用Resource资源文件

一、目的

       为了能够在DisplayAttribute中重复使用同样的名称,将所有的显示字符串集中管理。

二、方法

        1、DisplayAttribute本身支持直接使用资源文件。

[Display(ResourceType = typeof(Resource2), Name = "StudentName")]

  ResourceType为资源文件名,表示存在一个名称为"Resource2"的资源文件,其中有一个Key的名称为"StudentName"

    public class Student
    {
        [Required(ErrorMessageResourceType = typeof(Resource2), ErrorMessageResourceName = "StudentName")]
        [Display(ResourceType = typeof(Resource2), Name = "StudentName")]

        public virtual string Name { get; set; }

        [Display(ResourceType = typeof(Resource2), Name = "SortNumber")]
        public virtual long SortNumber { get; set; }

        [Display(ResourceType = typeof(Resource2), Name = "Remarks")]
        public virtual string Remarks { get; set; }
    }

  

     2、在Visual Studio 2017中直接创建一个Resource2的资源文件,后缀为"*.resx"。

    3、在代码中可直接使用Resource2,获取其中的key/value

string studentName = Resource2.StudentName;

三、将资源文件放在类库中管理

1、创建一个类库,名为ResourceClass

2、在类库中创建资源文件Resource

3、更改Resource.resx属性中的“自定义工具”为“PublicResXFileCodeGenerator”

原文地址:https://www.cnblogs.com/hahaxi/p/6771318.html