介绍属性与自定义属性、AttributeUsage

article/2025/9/30 4:31:27

介绍属性        
       属性为访问自定义类型的注释信息提供通用的访问方式。注释信息是随意的,换句话说,这种信息不是语言自身固有的,而是由你自己能够想象到的任何信息。你能使用属性(attributes)定义设计时信息(诸如文档)、运行时信息(诸如数据库字段名)、以及运行时行为特征(诸如假设成员是事务处理,或者能够参与事务处理)。在某种意义上,关联信息遵循与使用XML开发相同的原理。因为你能创建一个基于你所需的任何信息的属性,现有的一个标准机制适用定义属性自身和适合于查询成员或类型在运行时关于它们的附加属性。利用属性(attributes),我们能给类成员添加附加信息,因此我们能拥有一个完全自声明的组件。
        简单地在目标类型或成员前面的中括号([])指定属性数据,可以向C#类型或成员附加上一个定义属性。

定义属性
      属性(Attribute)实际是一个从类System.Attribute派生的类。类System.Attribute包含了一些为访问和测试定制属性的有用的方法。
      当给一个类型或成员附加上属性时,不用包含后缀Attribute。这是一种快捷方式,由C#语言的设计者协助插入。当编译器发现一个属性是附加在类型或成员上的时,自动用指定的属性名检索System.Attribute派生类。若编译器不能定位类,编译器将向指定的属性名追加Attribute。因而,定义属性类的通用惯例是:定义属性类时已Attribute结尾,并且省略部分名称。
      示例:

using System;
using System.Reflection;

public enum RegHives
{
    HKEY_CLASSES_ROOT,
    HKEY_CURRENT_USER,
    HKEY_LOCAL_MACHINE,
    HKEY_USERS,
    HKEY_CURRENT_CONFIG
}


public class RegKeyAttribute : Attribute
{
    
public RegKeyAttribute(RegHives Hive, String ValueName)
    
{
        
this.Hive = Hive;
        
this.ValueName = ValueName;
    }


    
protected RegHives hive;
    
public RegHives Hive
    
{
        
get return hive; }
        
set { hive = value; }
    }


    
protected String valueName;
    
public String ValueName
    
{
        
get return valueName; }
        
set { valueName = value; }
    }

}



[RegKey(RegHives.HKEY_CURRENT_USER, 
"SomeClass")]
class SomeClass
{
    
public int Foo;
    
public int Bar;
}


public class TestResKeyAttribute
{
    
public static void Main()
    
{

    }

}



AttributeUsage属性

除了定制attributes之外,可以使用Attributes属性定义如何使用这些属性。例如:

[AttributeUsage( 
    validon, 
    AllowMultiple = allowmultiple, 
    Inherited = inherited
)] 

强烈推荐使用AttributeUsage属性将属性文档化,因此属性的用户能直接使用已命名的属性,而不用在源代码中查找公用的读/写字段和属性。

定义属性目标

 1 public  enum AttributeTargets
 2 {
 3     Assembly    = 0x0001,
 4     Module      = 0x0002,
 5     Class       = 0x0004,
 6     Struct      = 0x0008,
 7     Enum        = 0x0010,
 8     Constructor = 0x0020,
 9     Method      = 0x0040,
10     Property    = 0x0080,
11     Field       = 0x0100,
12     Event       = 0x0200,
13     Interface   = 0x0400,
14     Parameter   = 0x0800,
15     Delegate    = 0x1000,
16     All = Assembly │ Module │ Class │ Struct │ Enum │ Constructor │ 
17         Method │ Property │ Field │ Event │ Interface │ Parameter │ 
18         Delegate,
19
20     ClassMembers  =  Class │ Struct │ Enum │ Constructor │ Method │ 
21         Property │ Field │ Event │ Delegate │ Interface,
22 }
23

当使用Attribute属性时,能指定AttributeTargets.all(属性目标),因此属性能被附加到在枚举AttributeTargets列出的任意类型上。若未指定AttributeUsage属性,缺省值是AttributeTargets.All。属性AttributeTargets用来限制属性使用范围。
 1 [AttributeUsage(AttributeTargets.Class)]
 2 public  class RemoteObjectAttribute : Attribute
 3 {
 4
 5 }
 6
 7 [AttributeUsage(AttributeTargets.Method)]
 8 public  class TransactionableAttribute : Attribute
 9 {
10
11
12
13 }
14

 可以使用或(|)操作符组合属性目标枚举中列出的项。

 单一用途和多用途属性

可以使用AttributeUsage定义属性的单一用途或多用途。即确定在单个字段上使用单一属性的次数。在缺省情况下,所有属性都是单用途的。在AttributeUsage属性中,指定AllowMultiple为true,则允许属性多次附加到指定的类型上。例如:

 1 [AttributeUsage(AttributeTargets.All, AllowMultiple= true)]
 2 public  class SomethingAttribute : Attribute
 3 {
 4      public SomethingAttribute(String str)
 5      {
 6     }
 7 }
 8
 9 [Something("abc")]
10 [Something("def")]
11 class MyClass
12 {
13 }
14

 

指定继承属性规则

   在AttributeUsageAttribute属性的最后部分是继承标志,用于指定属性是否能被继承。缺省值是false。然而,若继承标志被设置为true,它的含义将依赖于AllowMultiple标志的值。若继承标志被设置为true,并且AllowMultiple标志是flag,则改属性将忽略继承属性。若继承标志和AllowMultiple标志都被设置为true,则改属性的成员将与派生属性的成员合并。

指定属性继承规则

AttributeUsage的最后一个参数是继承标志,指出速航行是否可以被继承。如果设为true,它的意义取决于AllowMultiple属性的值。

继承

AllowMultiple

结果

True

False

派生的属性覆盖基属性

True

True

派生的属性和基属性共存



范例:

 1 using System;
 2 using System.Reflection;
 3
 4 namespace AttribInheritance
 5 {
 6     [AttributeUsage(
 7         AttributeTargets.All, 
 8         AllowMultiple =  true,
 9          // AllowMultiple = false,
10         Inherited =  true
11     )]
12      public  class SomethingAttribute : Attribute
13      {
14          private  string name;
15          public  string Name
16         
17              get  return name; }
18              set  { name = value; }
19         }
20
21          public SomethingAttribute( string str)
22          {
23              this.name = str;
24         }
25     }
26
27      [Something("abc")]
28      class MyClass
29      {
30     }
31
32     [Something("def")]
33      class Another : MyClass
34      {
35     }
36
37      class Test
38      {
39         [STAThread]
40          static  void Main( string[] args)
41          {
42             Type type =
43                 Type.GetType("AttribInheritance.Another");
44              foreach (Attribute attr  in type.GetCustomAttributes( true))
45                  // type.GetCustomAttributes(false))
46              {
47                 SomethingAttribute sa = 
48                     attr  as SomethingAttribute;
49                  if ( null != sa)
50                  {
51                     Console.WriteLine(
52                         "Custom Attribute: {0}", 
53                         sa.Name);
54                 }
55             }
56
57         }
58     }
59 }
60

 

若AllowMultiple设置为false,结果是:

Custom Attribute: def

 若AllowMultiple设置为true,结果是:

Custom Attribute: def

Custom Attribute: abc

注意,如果将false传递给GetCustomAttributes,它不会搜索继承树,所以你只能得到派生的类属性。


http://chatgpt.dhexx.cn/article/IR8AKxhY.shtml

相关文章

理解AttributeUsage类

类定义: // 摘要: // 指定另一特性类的用法。 此类不能被继承。[Serializable][AttributeUsage(AttributeTargets.Class, Inherited true)][ComVisible(true)]public sealed class AttributeUsageAttribute : Attribute{// 摘要: // 用指定的 System.Attri…

AttributeUsage属性

除了定制 attributes 之外&#xff0c;可以使用 Attributes 属性定义如何使用这些属性。例如&#xff1a;<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" /> [AttributeUsage( validon, AllowMultiple allowmultiple, …

AttributeUsage

AttributeUsage 【AttributeUsage】 System.AttributeUsage声明一个Attribute的使用范围与使用原则。 AllowMultiple 和 Inherited 参数是可选的&#xff0c;所以此代码具有相同的效果&#xff1a; AttributeTarget的值可以参考1。部分可取值如下&#xff1a; 如果 AllowMultip…

吉大软构件和中间件课程-JPA配置方法

吉大软构件和中间件课程-JPA配置方法 JPA连接方法&#xff1a; 1.standalone.xml 文字&#xff1a; <xa-datasource jta"true" jndi-name"java:jboss/datasources/MySqlDS" pool-name"MySqlDS" enabled"true" use-java-c…

JPA 配置文件最详细总结,没有之一!

又来了一个懵懂少年&#xff0c;看我怎么骗你的。 来我们开始学习吧。 PropertyPlaceholderConfigure 载入属性文件&#xff1a; 例如&#xff1a;class"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname"loc…

Spring Boot使用spring-data-jpa配置Mysql多数据源

转载请注明出处 :Spring Boot使用spring-data-jpa配置Mysql多数据源 我们在之前的文章中已经学习了Spring Boot中使用mysql数据库 在单数据源的情况下&#xff0c;Spring Boot的配置非常简单&#xff0c;只需要在application.properties文件中配置连接参数即可。 但是往往随…

SpringBoot 配置 JPA

新建项目 在application.properties配置文件中进行配置&#xff08;或者application.yaml中配置也行&#xff09; spring.datasource.urljdbc:mysql://localhost:3306/ssm?characterEncodingutf8&useSSLfalse&serverTimezoneUTC spring.datasource.usernameroot sp…

Springboot---JPA配置

1.在配置文件中写入数据库信息 application.properties配置如下 spring.datasource.primary.urljdbc:mysql://localhost:3306/test1 spring.datasource.primary.usernameroot spring.datasource.primary.passwordroot spring.datasource.primary.driver-class-namecom.mysql.…

spring-boot-starter-data-jpa 配置多个数据源与jpa实体类继承的问题、分页条件查询

JPA的继承注解一般有四种 MappedSuperclass 这个注解应用的场景是父类不对应任何单独的表&#xff0c;多个子类共用相同的属性。 注意&#xff1a; MappedSuperclass注解使用在父类上面&#xff0c;是用来标识父类的作用 MappedSuperclass标识的类表示其不能映射到数据库表&am…

Springboot多数据源+Jpa配置

随着业务复杂程度的增加&#xff0c;单一数据源越来越不满足具体的业务逻辑以及实现。 这里我用到了MySQL和Presto两种数据源&#xff1a; 多数据源配置GlobalDataSourceConfiguration&#xff1a; Configuration public class GlobalDataSourceConfiguration {Bean(name …

springboot--jpa 配置多数据库

使用spring boot jpa 配置多数据源 由于项目整合 以前的功能 但是以前功能存储的数据库是另一个数据库 这两天搜索了一下 遇见了许多坑 在这里记录一下 首先附上我的项目结构 可能有些乱 忘见谅。 pom.xml(把数据库的依赖引入) <!-- mariadb --><dependen…

Spring Data Jpa 配置多数据源

文章目录 1.配置数据库连接信息2.编写数据源配置类3.编写数据库配置4.目录结构 1.配置数据库连接信息 spring:datasource:db1: # 1.0 Datasourceurl: jdbc:mysql://127.0.0.1:3306/test1?useSSLfalse&serverTimezoneGMT%2b8&characterEncodingutf8&connectTimeo…

springboot2+JPA 配置多数据源(不同类型数据库)

注意&#xff1a;看此篇文章之前&#xff0c;springbootjpa的配置环境应搭建好&#xff0c;不会搭可以自行百度。本文章主要讲述配置JPA多数据源。 1.数据源配置文件 application.properties # 数据源thirded&#xff08;oracle数据库&#xff09; spring.jpa.thirded.databa…

jpa配置(jpa配置连接池)

JPA的实体状态有哪些呢&#xff1f; 该接口拥有众多执行数据查询的接口方法&#xff1a; Object getSingleResult()&#xff1a;执行SELECT查询语句&#xff0c;并返回一个结果&#xff1b; List getResultList() &#xff1a;执行SELECT查询语句&#xff0c;并返回多个结果&…

SpringBoot系列之数据库初始化-jpa配置方式

上一篇博文介绍如何使用spring.datasource来实现项目启动之后的数据库初始化&#xff0c;本文作为数据库初始化的第二篇&#xff0c;将主要介绍一下&#xff0c;如何使用spring.jpa的配置方式来实现相同的效果 I. 项目搭建 1. 依赖 首先搭建一个标准的SpringBoot项目工程&am…

Jpa环境配置及入门(增删改查)

案例&#xff1a;客户的相关操作&#xff08;增删改查&#xff09; 1.分析&#xff1a; 1.搭建环境&#xff1a; 创建maven工程&#xff0c;导入相关坐标&#xff1b; 配置使用jpa的核心配置文件&#xff1b; 位置&#xff1b;需要配置到类路径下叫做 META-INF的文件夹下 命…

PHP多国语言开发:CodeIgniter 2PHP框架中的多国语言,语言包(i18n)库

PHP多国语言开发&#xff1a;CodeIgniter 2PHP框架中的多国语言&#xff0c;语言包&#xff08;i18n&#xff09;多国语言库 引言 我们在CodeIgniter开发中经常会碰到多国语言网站&#xff0c;这里我们就来介绍一种简单有效的多国语言的操作方法。 做什么 语言在地址中是这…

Win 10 添加多国语言

不同用户对电脑系统的语言需求也不一样&#xff0c;出于工作原因需要使用其它语言&#xff0c;比如外国友人需要使用英语&#xff0c;俄罗斯语言等&#xff0c;此时很多用户都以为要下载对应语言版本的系统&#xff0c;然后重新安装系统&#xff0c;其实Win10是支持多国语言的&…

手工编译Flex SDK 多国语言包

项目需要将目前版本提供给其它地区&#xff1a;台湾、日韩等&#xff0c;面临着项目语言的国际化问题。 语言代号&#xff1a; 大陆&#xff1a;zh_CN 台湾&#xff1a;zh_TW 香港&#xff1a;zh_HK … 例如想支持繁体&#xff0c;没有zh_TW语言包怎么办&#xff1f; fl…

DevExpress去除多国语言包

DevExpress作为windows开发中较为强大的第三方组件&#xff0c;能极大的提高编程效率和界面效果。但也要引用它较多的dll文件&#xff0c;它专门有个查看dll程序集依赖的工具&#xff0c;在VS的工具菜单下&#xff1a; 在VS的工具菜单内有"DevExpress Assembly Deploymen…