Java Annotations 和 C# Attributes 有什么异同? [英] What are the similarities and differences between Java Annotations and C# Attributes?

查看:37
本文介绍了Java Annotations 和 C# Attributes 有什么异同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 库,我正在考虑移植到 C#.Java 库广泛使用了注释(在构建时和运行时).

I have a Java library I'm considering porting to C#. The Java library makes extensive use of annotations (at both build time and run time.)

我从未使用过 C# 属性,但我知道它们大致相当于 Java 注释.

I've never used C# attributes, but understand that they are the rough equivalent of Java annotations.

如果我继续使用属性替换注释的端口,我需要知道什么?什么会是一样的?不同的?什么会咬我?

If I proceed with the port using attributes to replace annotations, what do I need to know? What's going to be the same? Different? What's going to bite me?

推荐答案

两种语言对元数据何时可访问的控制不同.

Control over when your metadata is made accessible is different between the two languages.

Java 提供了 java.lang.annotation.Retention 注释和 java.lang.annotation.RetentionPolicy enum 控制何时可以访问注释元数据.选择从 Runtime(最常见 - 保留在类文件中的注释元数据)到 Source(编译器丢弃的元数据)不等.你用这个标记你的自定义注释接口 - 例如:

Java provides the java.lang.annotation.Retention annotation and java.lang.annotation.RetentionPolicy enum to control when annotation metadata is accessible. The choices vary from Runtime (most common - annotation metadata retained in class files), to Source (metadata discarded by compiler). You tag your custom annotation interface with this - for example:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CLASS)
public @interface TraceLogging {
  // etc
}

允许您在运行时反映您的自定义 TraceLogging 注释.

would allow you to reflect on your custom TraceLogging annotation at runtime.

C# 使用 ConditionalAttribute 属性 由编译时符号驱动.所以 C# 中的类似例子是:

C# uses the ConditionalAttribute attribute that is driven from compile time symbols. So the analogous example in C# is:

[Conditional("TRACE")]
public class TraceLoggingAttribute : Attribute
{
  // etc
}

这会导致编译器仅在定义了 TRACE 符号时为您的自定义 TraceLogging 属性吐出元数据.

which would cause the compiler to spit out the metadata for your custom TraceLogging attribute only if the TRACE symbol was defined.

注意.默认情况下,C# 中的属性元数据在运行时可用 - 仅当您想更改它时才需要.

这篇关于Java Annotations 和 C# Attributes 有什么异同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆