![](/img/trans.png)
[英]How to cast IDictionary<string, object> to IDictionary<string, MyType>
[英]How to find a specific value in an IDictionary<string, object>?
这个IDictionary<string, object>
包含我登录到 mongodb 的用户数据。 问题是TValue
是一个复杂的对象。 TKey
只是类名。
例如:
public class UserData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Admin NewAdmin { get; set; }
}
public class Admin
{
public string UserName { get; set; }
public string Password { get; set; }
}
目前,我正在尝试遍历Dictionary
并比较类型,但无济于事。 有没有更好的方法来做到这一点,还是我错过了标记?
var argList = new List<object>();
foreach(KeyValuePair<string, object> kvp in context.ActionArguments)
{
dynamic v = kvp.Value;
//..compare types...
}
只需使用OfType<>()
。 你甚至不需要钥匙。
public static void Main()
{
var d = new Dictionary<string,object>
{
{ "string", "Foo" },
{ "int", 123 },
{ "MyComplexType", new MyComplexType { Text = "Bar" } }
};
var s = d.Values.OfType<string>().Single();
var i = d.Values.OfType<int>().Single();
var o = d.Values.OfType<MyComplexType>().Single();
Console.WriteLine(s);
Console.WriteLine(i);
Console.WriteLine(o.Text);
}
输出:
Foo
123
Bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.