繁体   English   中英

什么是C#等效类 <Annotation> 从Java?

[英]What is the c# equivalent of Class<Annotation> from java?

编辑:提出问题的另一种方法:

  • 如果Java中的“ Class <Object> ”等效于C#中的“ Type
  • 什么是“ Class <Annotation> ”?

下面的代码来自我正在编写的Unity3D资产,因此c#的版本相当旧:“ Google告诉我,“大部分但不是全部是4.0”。

下面的代码有效(避免了不可避免的错误),我的问题是类型签名的表现力。 问题在于VisitAnnotatedFields()方法的签名,特别是attrType参数-该属性始终由Attribute的某些子类型提供。

在Java中,我将Java中的等效参数定义为“ Class <Annotation>”,以告知编译器调用者必须传递Annotation的子类型。

问题不是特定的注解,在其他情况下我也遇到过这个问题。 我只是通过检查和根据需要强制转换来解决此问题。

有没有一种方法可以用C#表示,或者我所有的类型引用都必须是“ Type”,并且我需要编写一堆文档和代码来检查是否传递了正确的信息?

示例代码:

[AttributeUsage(AttributeTargets.Field)]
public class NotNullAttribute : Attribute {
}

class NullReferenceCheck : SceneGameObjectCheck {
  public override IEnumerable<CheckFailure> Check(MonoBehaviour target){
    var failures = new List<CheckFailure>();
    ReflectionUtils.VisitAnnotatedFields(
      target,
      typeof(NotNullAttribute),
      (FieldInfo field, Attribute attr) => {
        // do the check for null value and add to failures
      });

    return failures;
  }
}

public static void VisitAnnotatedFields(
  MonoBehaviour target,
  Type attrType,
  Action<FieldInfo, Attribute> closure)
{
  IEnumerable<FieldInfo> fieldInfos = target.GetAllFields();
  foreach( var iField in fieldInfos ){
    object[] customAttributes = iField.GetCustomAttributes(false);
    foreach( var jAttr in customAttributes ){
      if( jAttr.GetType().IsAssignableFrom(attrType) ){
        closure.Invoke(iField, (Attribute) jAttr);
      }
    }
  }
}

虽然通常的答案是“否”-没有针对Type编译类型检查-我相信您仍然可以将泛型用于您的目的,例如:

public static void VisitAnnotatedFields<TAttribute>(
  MonoBehaviour target,
  Action<FieldInfo, TAttribute> closure)
  where TAttribute : Attribute
{
    IEnumerable<FieldInfo> fieldInfos = target.GetAllFields();
    foreach( var iField in fieldInfos ){
      object[] customAttributes = iField.GetCustomAttributes(false);
      foreach( var jAttr in customAttributes ){
        if( jAttr.GetType().IsAssignableFrom(typeof(TAttribute)) ){
          closure.Invoke(iField, (TAttribute) jAttr);
        }
      }
    }
}

并这样称呼它

ReflectionUtils.VisitAnnotatedFields(
  target,
  (FieldInfo field, NotNullAttribute attr) => {
    // do the check for null value and add to failures
  });

作为奖励,它将为您提供封闭内部本身的其他强类型。

如果我正确理解Java的Class<T> (“表示类型TClass对象”),则.NET中没有对应关系。

.NET中没有办法在编译时限制Type实例可以表示什么类型。 您必须进行运行时检查:

// using System.Diagnostics.Contracts;

void Foo(Type type)
{
    Contract.Requires(typeof(Attribute).IsAssignableFrom(type));
    // the above allows `type` to represent sub-types of `Attribute` as well.
    // if you want to allow only `Attribute`, change to `type == typeof(Attribute)`. 
    …
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM