Is is possible to implement setters on properties of anonymous types
Consider the following:
var o = new { Foo = "foo", Bar = "bar" };
This instance is read-only, since the anonymous type doesn't implement setters like a class does:
public class O
{
public String Foo { get; set; }
public String Bar { get; set; }
}
Is it possible to "open up" the anonymous instance and allow it's properties to be altered? Preferably in fewer characters than it would take to create a class.
I'm thinking perhaps this can be开发者_如何转开发 done with an extension method on Object; o.SetProperty(o.Foo, "foo!");
, if you can't implement setters in-line at the construction of the object.
No, cause anonymous types in C# are immutable by design.
Anonymous types are immutable by design, so there's no way you can change their state. You could use reflection (as Mark Gravell pointed out correctly) but neither is this desirable performance wise nor from a design perspective.
You've got multiple options to work around this:
- Use Tuples instead of annonymous types. Note that they are immutable too but you can work with them more easily to create methods like
tupleA.WithItem2(newValueForItem2)
. Similar to thestring
class. - write your own "named" type using auto properties, usually straightforward
- use a refactoring tool like CodeRush that can generate a "named" type from your usage
精彩评论