简体   繁体   中英

Create anonymous type from string

So I have a anonymous type which I have used ToString on, and put into a file. It looks like this (and remarkably like 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. 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 ; otherwise I'd probably just use a Dictionary<string, object> and change this:

RealObject.Name = AnonObject.Name;

to

RealObject["Name"] = AnonObject.Name;

(Or vice versa. It's not really clear what you're doing.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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