Ehs*_*rdi 1 c# dynamic-class-creation
我写了一个创建字典的方法。我需要将这本字典转换为一个类。
字典示例
Dictionary<string, dynamic> myDictionary = new Dictionary<string, dynamic> {
{ "ID1", 12 },
{ "ID2", "Text2"},
{ "ID3", "Text3" }
};
Run Code Online (Sandbox Code Playgroud)
这是需要创建的类的示例:
public class Foo
{
public int ID1 { get; set; }
public string ID2 { get; set; }
public string ID3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您的要求没有明确说明,但我猜您正在寻找一种动态类型,该类型的属性的名称映射到字典键。
在这种情况下,您可以使用像这样的简单字典包装器:
class DynamicDictionaryWrapper : DynamicObject
{
protected readonly Dictionary<string,object> _source;
public DynamicDictionaryWrapper(Dictionary<string,object> source)
{
_source = source;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
return (_source.TryGetValue(binder.Name, out result));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以这样使用:
public static void Main()
{
var myDictionary = new Dictionary<string, dynamic> {
{ "ID1", 12 },
{ "ID2", "Text2"},
{ "ID3", "Text3" }
};
dynamic myObject = new DynamicDictionaryWrapper(myDictionary);
Console.WriteLine(myObject.ID1);
Console.WriteLine(myObject.ID2);
Console.WriteLine(myObject.ID3);
}
Run Code Online (Sandbox Code Playgroud)
输出:
12
Text2
Text3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12784 次 |
| 最近记录: |