NSObject.FromObject的反转是什么,例如,从NSObject中取回常规C#对象。可以理解,这只适用于简单类型。
更新。让我说我甚至知道类型 - 但不是在运行时之前。我试过了
Convert.ChangeType (value, info.PropertyType, null)
但是我收到一条消息“值不是可转换对象:MonoMac.Foundation.NSString到System.String”。
更新2. FromObject如何运作:
using MonoMac.ObjCRuntime;
using System;
using System.Drawing;
public static NSObject FromObject (object obj)
{
NSObject result;
if (obj == null)
{
result = NSNull.Null;
}
else
{
Type type = obj.GetType ();
if (type == typeof(NSObject) || type.IsSubclassOf (typeof(NSObject)))
{
result = (NSObject)obj;
}
else
{
switch (Type.GetTypeCode (type))
{
case 3:
result = new NSNumber ((bool)obj);
return result;
case 4:
result = new NSNumber ((ushort)((char)obj));
return result;
case 5:
result = new NSNumber ((sbyte)obj);
return result;
case 6:
result = new NSNumber ((byte)obj);
return result;
case 7:
result = new NSNumber ((short)obj);
return result;
case 8:
result = new NSNumber ((ushort)obj);
return result;
case 9:
result = new NSNumber ((int)obj);
return result;
case 10:
result = new NSNumber ((uint)obj);
return result;
case 11:
result = new NSNumber ((long)obj);
return result;
case 12:
result = new NSNumber ((ulong)obj);
return result;
case 13:
result = new NSNumber ((float)obj);
return result;
case 14:
result = new NSNumber ((double)obj);
return result;
case 18:
result = new NSString ((string)obj);
return result;
}
if (type == typeof(IntPtr))
{
result = NSValue.ValueFromPointer ((IntPtr)obj);
}
else
{
if (type == typeof(SizeF))
{
result = NSValue.FromSizeF ((SizeF)obj);
}
else
{
if (type == typeof(RectangleF))
{
result = NSValue.FromRectangleF ((RectangleF)obj);
}
else
{
if (type == typeof(PointF))
{
result = NSValue.FromPointF ((PointF)obj);
}
else
{
INativeObject nativeObject = obj as INativeObject;
if (nativeObject != null)
{
result = Runtime.GetNSObject (nativeObject.Handle);
}
else
{
result = null;
}
}
}
}
}
}
}
return result;
}
答案 0 :(得分:2)
就像FromObject
转换一样,您必须逐个处理。
对于NSNumber
s,使用显式转换(也适用于bool):
NSNumber number;
double d = (double)number;
对于NSString
,隐式转换甚至工作:
NSString nsstring;
string converted = nsstring;
但我想你已经计算过价值类型的转换。
对于引用类型,从NSObject
派生的所有类型(对于大多数要反复传递给本机的对象的情况而言)都有一个构造函数重载,需要IntPtr
作为论点。用那个。
NSObject native;
var label = new UILabel (native.Handle);
话虽如此,NSObject
是多余的。您的本机库可能只返回您可用于重新创建对象的IntPtr
(void*
)。你不必这样做:
IntPtr ptr;
NSObject nsobject = new NSObject (ptr);