Dynamic property assessment

In DLR, I would like to do something like this:

class MyClass { int MyProperty { get; set; } } 

In a razor I would do something like this. ( InstanceOfMyClass is some dynamic object that looks at an instance of MyClass )

 @InstanceOfMyClass.MyProperty 

This displays a string representation of MyProperty .

Now if I do it.

 @InstanceOfMyClass.MyMissingProperty 

I would like for him to display "Missing: MyMissingProperty". I would like to capture the whole expression, for example.

 @InstanceOfMyClass.MyMissingProperty.MoreMissing 

It might be possible to output "Missing: MyMissingProperty.MoreMissing", but this may require a lot of DLR.

Will ExpandoObject allow me to do this? If not, what do I need to do to implement this?

+4
source share
3 answers

Extend DynamicObject.TryGetMember with this:

If the member exists, return the value. If the member does not exist, return a new instance of the class that will handle both the string representation of the missing property and the chain. Something like that

 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 have not tried it, but I think that this will give you an idea of ​​how to solve the problem.

Hope this helps.

+3
source

I'm not sure about Expando, it is rather used when you want to set a property and then get it. However, from what you write, it seems that you would like to read any value that has not been previously set.

You can use DynamicObject for this. You just override TryGetMember .

0
source

You could achieve this by creating your own version of DynamicObject and then reloading TryGetMember

http://haacked.com/archive/2009/08/26/method-missing-csharp-4.aspx

0
source

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


All Articles