Monotouch: convert an Object to NSObject

三世轮回 提交于 2019-12-18 05:38:13

问题


How is it possible to convert an Object instance to NSObject one?

I've created a NSDictionary from

NSDictionary.FromObjectAndKey();

This method wants an NSObject but I have custom object to pass in:

int key = 2341;
var val = new MyClass();
NSDictionary.FromObjectAndKey(val, key); // obviously it does not work!!

How to fix this? Thank you in advance.


回答1:


You can not convert an arbitrary object into an NSObject. The NSObject.FromObject will try to wrap common data types like numbers, strings, rectangles, points, transforms, and a handful of other .NET types into their equivalent NSObject types.

In your particular example, "MyClass" would have to derive from an NSObject before you could use it in the NSDictionary.




回答2:


The easiest solution I could find was to wrap the .Net object in an NSObject, then unwrap as needed.

public class NSObjectWrapper : NSObject
{
    public object Context;

    public NSObjectWrapper (object obj) : base()
    {
        this.Context = obj;
    }

    public static NSObjectWrapper Wrap(object obj)
    {
        return new NSObjectWrapper(obj);
    }
}

Example use:

// wrap
var myNSObj = NSObjectWrapper.Wrap(new MyClass());
// unwrap
var myObj = myNSObj.Context as MyClass;



回答3:


This is the way:

NSDictionary.FromObjectAndKey(NSObject.FromObject(val), NSObject.FromObject(key));


来源:https://stackoverflow.com/questions/5664321/monotouch-convert-an-object-to-nsobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!