Here is my scenario... I want to have some base class and have some set of extension methods to this class that will be hosted probably in different assemblies. Depending on what assemblies added to the project, different properties should be calculated and stored inside.
I have some base class
public class AObject
{
public string PropertyA { get; set; }
public int PropertyB { get; set; }
}
and do have some extension method to this class
public static class AObjectExtensions
{
public static void DoSomething(this AObject a, string value)
{
a.PropertyC = value;
}
}
What I want to get, I want to do some calculations inside extension method DoSomething
and save results as PropertyC
inside AObject
. AObject
doesn't have PropertyC
by default, so I want to add it dynamically. I figured out that to work with dynamic properties I have to use ExpandoObject
, but not sure that I see how it can be used here...
So, the main question is it a good scenario at all or I have to think about something else?
You need to inherit your object from
DynamicObject
:Your extension method has to be changed to:
You have the ability to iterate over all dynamic members using
GetDynamicMemberNames()
and ifAObject
provides an indexer or a getter method that accessesthis._members
you can access to all dynamic values.EDIT: There meight be a problem using this solution. I didn't tested it.
((dynamic)a).PropertyA
meight be hidden byTry(Get|Set)Member
. If so you can change the getter and setter ofPropertyA
andProprertyB
to access the_members
or you can handle this cases inTry(Get|Set)Member
. Adding these properties to_member
opens up the possibility to iterate over these members too.