Is this a smart way to use C # dynamic?

Forgive a rude example. I have an encoder that returns an interface. Instead of using "is" and "as" to get an object that implements the interface, I would like to use dynamic to access the field property of the object. The field property is NOT on the interface, but is common to all objects that implement the interface.

EDIT: I should also mention that I have no control over the encoder or interfaces, so I cannot modify them.

public class Program { public Program() { dynamic temp = GetInterface(); string s = temp.Blah; temp.Blah = s; } private ITest GetInterface() { return new Test(); } } public interface ITest { } public class Test : ITest { public string Blah { get; set; } } 
+4
source share
5 answers

This is not a good example. If all (or many) interface implementations have a field, then create an abstract interface implementation with a field, implement implementations from an abstract class, and do not inherit the interface. Then you can use an abstract class, not an interface.

+4
source

Use will work fine. The dynamic binding will look at the type and find the underlying property. From this point of view, it really is.

However, if this is a property that is common to all implementations of an interface, then why not just add it to the interface? If this is a property that you prefer not to publish, then why not have a second internal interface that contains the property?

+3
source

Yes, which is acceptable and will compile. However, it looks like an anti-pattern in my point of view. What happens when you once rename a Blah property in a class? Of course, it will compile, but ...

Note: from your edit, I understand that you cannot add a property to ITest. Therefore, I would create a new "ITest2" interface with a property that Test implements, and let the compiler do your work.

+1
source

In the specific case you were talking about, it looks like the property must be a member of the interface.

0
source

Why not add Blah to ITest ? I.e:

 public interface ITest { public string Blah { get; set; } } 
0
source

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


All Articles