什么是Java注解和C#属性之间的异同? [英] What are the similarities and differences between Java Annotations and C# Attributes?

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

问题描述

我有我正在考虑移植到C#中的Java库。 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提供的<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/annotation/Retention.html\">java.lang.annotation.Retention注释和<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/annotation/RetentionPolicy.html\">java.lang.annotation.RetentionPolicy枚举以控制在批注元数据访问。这些选择从运行变化(最常见的 - 保留在类文件注解元数据),以来源(元数据被编译器丢弃)。你这个标记您的自定义注释界面 - 例如:

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 注释。

C#使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx\">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
}

这将导致编译器吐出的元数据为您定制 TraceLogging 属性只有在 TRACE 符号是定义。

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

NB。属性的元数据在运行时可默认在C#中 - 这一点,如果你想改变时才需要

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

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