Xamarin.iOS,将 Dictionary 转换为 NSDictionary
Posted
技术标签:
【中文标题】Xamarin.iOS,将 Dictionary 转换为 NSDictionary【英文标题】:Xamarin.iOS, convert Dictionary to NSDictionary 【发布时间】:2016-07-01 20:27:52 【问题描述】:我正在尝试将 Branch.io 集成到我的 Xamarin 项目中,并且遇到了将 c# 的 Dictionary 转换为 NSDictionary 的要求。
试过
字典作为 NSDictionary //没用也试过了
private NSMutableDictionary BranchData (Dictionary<string, object> data)
List<string> keys = data.Keys.ToList();
NSMutableDictionary branchData = new NSMutableDictionary ();
foreach (string key in keys)
branchData.Add (new NSString(key), data[key] as NSObject);
return branchData;
没用。
任何线索都会有所帮助。谢谢!
更新:
https://***.com/a/5664785/344798
【问题讨论】:
【参考方案1】:这就是我将字典转换为 NSDictionary 的方式
var iconattrs = new Dictionary<string, string>
"ITEMTYPE", "DIVESITE",
"LOCATION", diveSite.Location,
"DESCRIPTION", diveSite.BriefDescription,
"LINK", diveSite.Link,
"ID", diveSite.ID.ToString()
;
var myResult = NSDictionary.FromObjectsAndKeys(iconattrs.Values.ToArray()
,iconattrs.Keys.ToArray())
【讨论】:
嗨,我怎样才能把它倒过来?我的意思是 NSDictionary 到 Dictionary这对我有用..当然可以优化或者更智能:
private static NSMutableDictionary ConvertToNativeDictionary(Dictionary<string, object> dict)
NSMutableDictionary newDictionary = new NSMutableDictionary();
try
foreach (string k in dict.Keys)
var value = dict[k];
try
if (value is string)
newDictionary.Add((NSString)k, new NSString((string)value));
else if (value is int)
newDictionary.Add((NSString)k, new NSNumber((int)value));
else if (value is float)
newDictionary.Add((NSString)k, new NSNumber((float)value));
else if (value is nfloat)
newDictionary.Add((NSString)k, new NSNumber((nfloat)value));
else if (value is double)
newDictionary.Add((NSString)k, new NSNumber((double)value));
else if (value is bool)
newDictionary.Add((NSString)k, new NSNumber((bool)value));
else if (value is DateTime)
newDictionary.Add((NSString)k, ((DateTime)value).DateTimeToNSDate());
else
newDictionary.Add((NSString)k, new NSString(value.ToString()));
catch (Exception Ex)
if (value != null)
Ex.Data.Add("value", value);
Logger.LogException(Ex);
continue;
catch (Exception Ex)
Logger.LogException(Ex);
return newDictionary;
这是 NSDate 转换:
public static class NSDateExtensions
public static DateTime NSDateToDateTime(this NSDate date)
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0));
return reference.AddSeconds(date.SecondsSinceReferenceDate);
public static NSDate DateTimeToNSDate(this DateTime date)
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0));
return NSDate.FromTimeIntervalSinceReferenceDate(
(date - reference).TotalSeconds);
【讨论】:
以上是关于Xamarin.iOS,将 Dictionary 转换为 NSDictionary的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin.iOS:如何将 NavigationBar 添加到视图
Xamarin.iOS VSTS 无法将临时钥匙串添加到钥匙串搜索路径
如何使用 Xamarin.iOS 将广告内容分配给 stacklayout