c# - Xamarin.iOS 上的 MakeGenericMethod/MakeGenericType

标签 c# ios iphone xamarin.ios xamarin

我试图弄清楚从 Xamarin 部署 iOS 时的限制到底意味着什么。

http://developer.xamarin.com/guides/ios/advanced_topics/limitations/

我的印象是您没有 JIT,因此任何 MakeGenericMethod 或 MakeGenericType 都无法工作,因为这需要 JIT 编译。

我还了解到,在模拟器上运行时,这些限制不适用,因为模拟器未在完整的 AOT(提前)模式下运行。

在设置我的 Mac 以便我可以部署到我的手机之后,除了以下测试在实际设备 (iPhone) 上运行时会失败之外。

    [Test]
    public void InvokeGenericMethod()
    {
        var method = typeof(SampleTests).GetMethod ("SomeGenericMethod");

        var closedMethod = method.MakeGenericMethod (GetTypeArgument());

        closedMethod.Invoke (null, new object[]{42});

    }

    public static void SomeGenericMethod<T>(T value)
    {
    }


    private Type GetTypeArgument()
    {
        return typeof(int);
    }

事情是成功完成的,我真的不明白为什么。这段代码不需要JIT编译吗?

为了“让它崩溃”,我还用 MakeGenericType 做了一个测试。

    [Test]
    public void InvokeGenericType()
    {
        var type = typeof(SomeGenericClass<>).MakeGenericType (typeof(string));

        var instance = Activator.CreateInstance (type);

        var method = type.GetMethod ("Execute");

        method.Invoke (instance, new object[]{"Test"});

    }


public class SomeGenericClass<T>
{
    public void Execute(T value)
    {

    }
}

如果没有 JIT,这怎么行?

我错过了什么吗?

最佳答案

为了使代码失败,请转到 iOS 项目选项,选择“iOS 构建”并将“链接器行为:”更改为“链接所有程序集”。运行代码将导致异常,它将是未找到类型 XXX 的默认构造函数类型。

现在,在您的代码中引用 SomeGenericClass{string},该方法将正常运行。添加的两行导致编译器在二进制文件中包含 SomeGenericClass{string}。请注意,这些行可以在编译为二进制文件的应用程序中的任何位置,它们不必位于同一函数中。

    public void InvokeGenericType()
    {
        // comment out the two lines below to make the code fail
        var strClass = new SomeGenericClass<string>();
        strClass.Execute("Test");

        var type = typeof(SomeGenericClass<>).MakeGenericType (typeof(string));

        var instance = Activator.CreateInstance (type);

        var method = type.GetMethod ("Execute");

        method.Invoke (instance, new object[]{"Test"});
    }

关于c# - Xamarin.iOS 上的 MakeGenericMethod/MakeGenericType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588090/

相关文章:

c# - 如何获取用户的桌面完整地址?

c# - 组合两个 Linq 表达式

c# - 赋值的左侧必须是变量

javascript - 从 iOS UIWebView 更新 React 组件中元素的值

ios - 结构默认初始化程序不触发 didSet

c# - 中继器内的中继器

ios - 对 NSURLRequest 进行排队以模拟同步、阻塞请求

iphone - 滚动时感觉滞后,同时从后台线程中的 Assets 加载全屏图像

ios - 来自 iOS 设备的 Azure Blob 存储 : Server failed to authenticate the request

ios - UIScrollView 没有在 Swift 中正确添加 subview