简体   繁体   English

从字符串创建匿名类型

[英]Create anonymous type from string

So I have a anonymous type which I have used ToString on, and put into a file. 因此,我有一个匿名类型,使用了ToString并将其放入文件中。 It looks like this (and remarkably like JSon...): 看起来像这样(非常像JSon ...):

{ Name = Name, Description = Description, Status = Pending, Key = Template, SubmittedBy = MyName, Identity = 2fb7a40b-e07a-4f1a-a48b-2c2720567f35 }

now I want to go the other way (edit:take the string from a file and put it into a format I can put into a known object) and put it into an anonymous type (which has the same properties, but I don't care if they are castable or anything like that, I just want a quick way to do something like. 现在,我想换一种方式(编辑:从文件中获取字符串,并将其放入可以放入已知对象的格式中),然后将其放入匿名类型(具有相同的属性,但是我没有关心它们是否可铸或类似的东西,我只想一种快速的方法来做类似的事情。

AnonObject = GetObjectFromFile(blah);
RealObject.Name = AnonObject.Name;

I only have an interface for RealObject, so I can't add serialisation to the class. 我只有RealObject的接口,因此无法向该类添加序列化。 If you know a better way, let me know. 如果您知道更好的方法,请告诉我。 Thanks. 谢谢。

Anonymous types are defined at compile time, and included in the assembly just like any other type. 匿名类型是在编译时定义的,并且与其他任何类型一样,都包含在程序集中。 Creating them at execution time would require dynamically creating types - it's likely to end up getting messy really quickly. 在执行时创建它们将需要动态创建类型-最终可能很快就会变得混乱。

If you're using .NET 4, you could use an ExpandoObject and dynamic ; 如果使用的是.NET 4,则可以使用ExpandoObjectdynamic ; otherwise I'd probably just use a Dictionary<string, object> and change this: 否则,我可能只使用Dictionary<string, object>并更改它:

RealObject.Name = AnonObject.Name;

to

RealObject["Name"] = AnonObject.Name;

(Or vice versa. It's not really clear what you're doing.) (反之亦然。目前尚不清楚您在做什么。)

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

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