小编Rhi*_*vel的帖子

如何在C#中按字符串访问类成员?

有没有办法通过字符串(名称)访问成员?

例如,如果静态代码是:

classA.x = someFunction(classB.y);
Run Code Online (Sandbox Code Playgroud)

但我只有两个字符串:

string x = "x";
string y = "y";
Run Code Online (Sandbox Code Playgroud)

我知道在JavaScript中你可以做到:

classA[x] = someFunction(classB[y]);
Run Code Online (Sandbox Code Playgroud)

但是如何在C#中做到这一点?

此外,是否可以按字符串定义名称?

例如:

string x = "xxx";
class{
   bool x {get;set}  => means bool xxx {get;set}, since x is a string
}
Run Code Online (Sandbox Code Playgroud)

更新,对于tvanfosson,我无法让它工作,它是:

public class classA
{
    public string A { get; set; }
}
public class classB
{
    public int B { get; set; }
}

var propertyB = classB.GetType().GetProperty("B");
var propertyA = classA.GetType().GetProperty("A");
propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB, null) as …
Run Code Online (Sandbox Code Playgroud)

c# reflection class

8
推荐指数
1
解决办法
5501
查看次数

如何为 Dictionary<string, T> 禁用 Nancy 的 JSON 到 C# 类自动大小写转换?

对于在 C#JavaScript 中表示字典的对象,如何在从 JSON 序列化和反序列化期间禁用 Nancy 在骆驼和 Pascal 大小写之间的自动转换?

在我的例子中,这些字典的键是不能被自动大小写转换更改的 ID。

此外,这些字典本身就是其他对象的属性名称/键的值。

下面是一个例子JavaScript对象,其中,I为所述对象的自动大小写转换(.customers.Customers.addresses.Addresses),而不是用于ID值的子对象键(ID33100a00abc433D123等):

{
    customers: {
        ID33100a00: 'Percy',
        abc433D123: 'Nancy'
    },
    addresses: {
        abc12kkhID: 'Somewhere over the rainbow',
        JGHBj45nkc: 'Programmer\'s hell',
        jaf44vJJcn: 'Desert'
    }
}
Run Code Online (Sandbox Code Playgroud)

这些字典对象Dictionary<string, T>在 C#中都用 表示,例如:

Dictionary<string, Customer> Customers;
Dictionary<string, Address> Addresses;
Run Code Online (Sandbox Code Playgroud)

不幸的设定

JsonSettings.RetainCasing = true;
Run Code Online (Sandbox Code Playgroud)

根本不会导致自动大小写转换。

我还尝试JavaScriptConverter 按照Nancy 文档中的描述编写自己的内容来解决该问题,但是对象键的字符串的实际序列化/反序列化发生在其他地方(因为转换器不直接处理 JSON 字符串,而是IDictionary<string, object>对象) . …

c# json dictionary nancy

5
推荐指数
1
解决办法
1768
查看次数

将Dictionary <T1,T2>的所有内容添加到另一个Dictionary <T1,T2>(键和值的相同类型)的最简单方法是什么?

有没有比使用下面示例中的两个选项之一复制/添加source字典的所有内容更简单的方法destination Dictionary<T1, T2>

Dictionary<string, int> source = new Dictionary<string, int>(),
    destination = new Dictionary<string, int>();

source.Add("Developers", 1);
source.Add("just", 2);
source.Add("wanna have", 3);
source.Add("FUN!", 4);

// Option 1 (feels like a hack):
//
source.All(delegate(KeyValuePair<string, int> p)
{
    destination.Add(p.Key, p.Value);
    return true;
});

// Option 2:
//
foreach (string k in source.Keys)
{
    destination.Add(k, source[k]);
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是类似的东西.ForEach().

c#

0
推荐指数
1
解决办法
125
查看次数

标签 统计

c# ×3

class ×1

dictionary ×1

json ×1

nancy ×1

reflection ×1