【问题标题】:Add boolean class to array of classes将布尔类添加到类数组
【发布时间】:2015-03-27 10:54:16
【问题描述】:

我有一些用 Java 编写的代码,我想将其转换为 Xamarin (C#)。我如何用 C# 编写这个?

private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class, Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };

我不知道如何获得这个“boolean.class”和“>”也不起作用。 因为这样就会被调用

Method mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature);

然后为每个喜欢的一些包装器

if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        invokeMethod(mStartForeground, mStartForegroundArgs);
        return;
    }

【问题讨论】:

    标签: java c# class xamarin


    【解决方案1】:

    相当于Class&lt;T&gt; 的c# 是Type,对于boolean.class 它是typeof(bool) - 如果您想了解更多关于c# 反射的信息,请查看this tutorial。这是翻译后的代码:

  • 签名:
    private static readonly Type[] mSetForegroundSignature = new Type[] { typeof(bool) };
    private static readonly Type[] mStartForegroundSignature = new Type[] { typeof(int), typeof(Notification) };
    private static readonly Type[] mStopForegroundSignature = new Type[] { typeof(bool) };
    

  • 获取方法对象:
    System.Reflection.MethodInfo mStartForeground = new this.GetType().GetMethod("startForeground", mStartForegroundSignature);
    

  • 调用方法:
    if(mStartForeground != null) {
        mStartForegroundArgs[0] = Convert.ToInt32(id);
        mStartForegroundArgs[1] = notification;
        //invoke via reflection (it may be different to invokeMethod?)
        mStartForeground.Invoke(instance, mStartForegroundArgs);
        return;
    }
    
  • 【讨论】:

    • 感谢您的评论,但在这种情况下,它给了我。调用此错误“对象类型 Java.Lang.Integer 无法转换为目标类型:System.Int32”私有 Java .Lang.Object[] mStartForegroundArgs = new Java.Lang.Object[2];是 mStartForegroundArgs 的类型
    • 我不知道Java.Lang.ObjectJava.Lang.Integer 在.NET 中应该指什么,但是Convert.ToInt32 不是将id 转换为整数的正确方法...
    【解决方案2】:

    在 C# 中,它被称为 Type 而不是 Class。事物的名称略有不同:

    private static readonly Type[] mSetForegroundSignature = new Type[] { typeof(bool) }; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2013-08-07
      • 2016-08-16
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      相关资源
      最近更新 更多