相关疑难解决方法(0)

c#Reflection - 查找集合的通用类型

我正在反映一个属性'Blah',它的Type是ICollection

    public ICollection<string> Blah { get; set; }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var pi = GetType().GetProperty("Blah");
        MessageBox.Show(pi.PropertyType.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

这给了我(正如你所期待的那样!)ICollection<string>......

但我真的想要收集类型即ICollection(而不是ICollection<string>) - 有谁知道我该怎么做呢?

c# reflection types properties

21
推荐指数
2
解决办法
2万
查看次数

测试对象是否是C#中的字典

有没有办法测试对象是否是字典?

在一个方法中,我试图从列表框中的选定项目中获取值.在某些情况下,列表框可​​能绑定到字典,但在编译时不知道.

我想做类似的事情:

if (listBox.ItemsSource is Dictionary<??>)
{
    KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
    object value = pair.Value;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在运行时使用反射动态地执行此操作?我知道可以使用泛型类型的反射并确定键/值参数,但我不确定在检索这些值之后是否有办法完成其余的操作.

c# reflection collections dictionary

15
推荐指数
3
解决办法
1万
查看次数

模型绑定到Nancy中的Dictionary <string,string>

我无法Dictionary<string,string>在Nancy中绑定JSON .

这条路线:

Get["testGet"] = _ =>
{
    var dictionary = new Dictionary<string, string>
    {
         {"hello", "world"},
         {"foo", "bar"}
    };

    return Response.AsJson(dictionary);
};
Run Code Online (Sandbox Code Playgroud)

按预期返回以下JSON:

{
    "hello": "world",
    "foo": "bar"
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将这个确切的JSON发布回此路线时:

Post["testPost"] = _ =>
{
    var data = this.Bind<Dictionary<string, string>>();
    return null;
};
Run Code Online (Sandbox Code Playgroud)

我得到了例外:

值"[Hello,world]"不是"System.String"类型,不能在此通用集合中使用.

是否可以绑定到Dictionary<string,string>使用Nancys默认模型绑定,如果是这样,我在这里做错了什么?

c# model-binding nancy

6
推荐指数
1
解决办法
2452
查看次数