简体   繁体   English

将PSObject实例解析为C#对象

[英]Parse an PSObject instance to a C# object

How can I parse an PSObject instance to a C# POCO model entity? 如何将PSObject实例解析为C# POCO模型实体?

The PSObject instance is a dynamic object that contains these properties: PSObject实例是一个动态对象,其中包含以下属性:

@{Name=David;  Diff=0.0268161397964839; File=Output.txt}

I have C# POCO model that fits those fields. 我有适合这些领域的C#POCO模型。

Is there a nice way to cast? 有铸造的好方法吗?

You either need to convert the PSObject instance to some common representation or iterate over PSObject.Properties and fill the fields of the POCO using reflection. 您要么需要将PSObject实例转换为某种通用表示形式,要么需要遍历PSObject.Properties并使用反射填充POCO的字段。

This simple serialize-deserialize code with Newtosoft.Json implements the first way and may work well for simple cases: 用Newtosoft.Json编写的这个简单的序列化/反序列化代码可以实现第一种方法,并且可以在简单的情况下很好地工作:

public class MyInfo
{
    public string Name { get; set; }
    public double Diff { get; set; }
    public string File { get; set; }
}

static void Main(string[] args)
{
    PSObject obj = PSObject.AsPSObject(new { Name = "David", Diff = 0.2, File = "output.txt" });

    var serialized = JsonConvert.SerializeObject(obj.Properties.ToDictionary(k => k.Name, v => v.Value));
    Console.WriteLine(serialized);

    var deseialized = JsonConvert.DeserializeObject<MyInfo>(serialized);
    Console.WriteLine($"Name: {deseialized.Name}");
    Console.WriteLine($"Diff: {deseialized.Diff}");
    Console.WriteLine($"File: {deseialized.File}");
}

Output: 输出:

{"Name":"David","Diff":0.2,"File":"output.txt"}
Name: David
Diff: 0,2
File: output.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM