Reputation: 190944
With the DLR, i would like to do something like this:
class MyClass {
int MyProperty { get; set; }
}
In razor, I would do something like this. (InstanceOfMyClass
is some dynamic object that looks at an instance of MyClass
)
@InstanceOfMyClass.MyProperty
This would output the string representation of MyProperty
.
Now if I do this.
@InstanceOfMyClass.MyMissingProperty
I would like it to output "Missing: MyMissingProperty". I would love to capture the whole expression, like so.
@InstanceOfMyClass.MyMissingProperty.MoreMissing
Could potentially output "Missing: MyMissingProperty.MoreMissing", but that might be asking a lot of the DLR.
Will the ExpandoObject
allow me to do this? If not, what do I have to do to implement this?
Upvotes: 4
Views: 494
Reputation: 14944
You could achieve that by creating your own version of DynamicObject then over-write the TryGetMember
http://haacked.com/archive/2009/08/26/method-missing-csharp-4.aspx
Upvotes: 0
Reputation: 8352
Extend DynamicObject.TryGetMember in this way:
If the member exists, return the value. If the member doesn't exist, return a new instance of a class that will handle both the string representation of the missing property and also the chain. Something like this
public class MissingPropertyChain : DynamicObject
{
private string property;
public MissingPropertyChain(string property)
{
this.property = property;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if(binder.Name == "ToString")
result = "Missing property: " + property;
else
result = new MissingPropertyChain( property + "." + binder.Name;
return true;
}
}
I didn't try it, but I think it will give you the idea of how to solve the problem.
Hope it helps.
Upvotes: 3
Reputation: 48230
I am not sure about the Expando, it's rather used when you want to set the property and then get it. From what you write, however, it seems that you'd like to be able to read any value which hasn't been set before.
For this, the DynamicObject
could be used. You just override the TryGetMember
.
Upvotes: 0