Is using shared Dictionaries a good solution to the lack of "extension properties"?
Suppose I have some extension methods but also need to extend the object's state. Seeing as there is no support for extension properties in C#, would using shared static Dictionary be a good solution?
For example something like this:
class Foo
{
// 3rd party class
}
static class Helper
{
private static Dictionary<Foo, Guid> guidDict = new Dictionary<Foo, Guid>();
public static void DoSomething(this开发者_开发知识库 Foo foo)
{
Guid guid = guidDict[foo];
// do stuff
}
public static void DoAnotherthing(this Foo foo)
{
Guid guid = guidDict[foo];
// do stuff
}
}
What are some other solutions?
I'm not sure that is a good idea; the synchronization would be a nightmare, and you'd need to use a key that didn't risk keeping all the objects alive forever (don't use the object-reference). Better to use a property bag inside the object, or wrap your object in something else that provides the missing properties. You could also use inheritance, but that has more limitations (you can encapsulate a sealed type or an interface). You can forward the members if you really want:
public class Foo {
private readonly Bar bar;
public Foo(Bar bar) { this.bar = bar; }
public int Id { get {return bar.Id; } set {bar.Id = value; } }
public string Name {get;set;}
}
If you need to extend an object's state then I'd recommend inheritance or composition.
You are correct in that you cannot maintain state with extension methods, but nor would you be able to with extension properties. They can only manipulate state in ways that you would otherwise have access to anyway.
However, I don't believe a static Dictionary will help either. It would be good possibly for maintaining shared state, but not an object's state. Are you doing something fancy like the following? There is a good unique identifier on each instantiated object, such that you could add a state variable to the dictionary that would be keyed to that object? That seems kindof round-about, if that's what you're attempting
Assuming you have no control over the class itself (hence the need to extend it in some way), can you inherit from this object? Then of course you can do what you need to do.
What's wrong with the usual solution of inheriting or object composition (decorator pattern) to add the properties that you need?
Would using shared static Dictionary be a good solution?
I don't think so. Aside from synchronization issues and global state issues, you also have ugly object lifetime issues:
{
MyObject o = new MyObject();
PropertyDictionary.Add(o, "SomeExtensionProperty", someValue);
}
Now o
is out of scope but the dictionary still has a reference to it! Yucky!
精彩评论