Is using common dictionaries a good solution to the problem of the lack of "extension properties"?

Suppose I have some extension methods, but it is also necessary to extend the state of the object. Seeing that C # does not support extension properties, would using a 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 other solutions?

+4
source share
4 answers

I'm not sure this is a good idea; synchronization would be a nightmare, and you will need to use a key that does not hurt to keep all objects permanently ( do not use a link to the object). It’s better to use the property package inside the object or wrap your object with something else that provides the missing properties. You can also use inheritance, but this has more limitations (you can encapsulate a private type or interface). You can redirect participants if you 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;} } 
+3
source

You are correct in that you cannot maintain state using extension methods, but you also cannot have the ability to expand. They can only manipulate how you could have access anyway.

However, I do not believe that a static dictionary will also help. It would be good, perhaps, to maintain the general state, but not the state of the object. Are you doing something like the following? Is there a unique unique identifier for each object object, so that you can add a state variable to the dictionary that will be bound to this object? It seems like a good round, if that's what you are trying

Assuming you have no control over the class itself (hence the need to extend it in some way), can you inherit this object? Then, of course, you can do what you need.

+1
source

If you need to extend the state of an object, I would recommend inheritance or composition .

+1
source

What is wrong with the usual solution of inheritance or composition of an object ( decorator template ) to add the properties you need?

Would using a shared static dictionary be a good solution?

I do not think so. Besides synchronization issues and global issues, you also have issues with ugly objects:

 { MyObject o = new MyObject(); PropertyDictionary.Add(o, "SomeExtensionProperty", someValue); } 

Now o goes out of scope, but the dictionary still has a link to it! Yucky!

+1
source

Source: https://habr.com/ru/post/1299016/


All Articles