-3

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...
}
4

1 回答 1

2

只需使用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

链接到小提琴

于 2018-08-22T21:13:03.363 回答