我试图将Branch.io集成到我的Xamarin项目中,并遇到了将c#的Dictionary转换为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;
}
没用。
任何线索都会有所帮助。谢谢!
更新
答案 0 :(得分:27)
这是我将字典转换为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())
答案 1 :(得分:0)
这对我有用..可以优化课程或更聪明:
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);
}
}