Using a C # variable of type dynamic in embedded code

It seems that creating an open property (returning an anonymous object) in your code for type "dynamic" and displaying it on your aspx page will convert the variable to type "object". It's right? Every time I try to do this, I get an exception saying

'object' does not contain a definition for val1

Here is an example:

    public dynamic showMe
    {
        get
        {
            return new
            {
                val1 = 5,
                val2 = "This is val2",
                val3 = new List<int>(){1,2,3,4,5}
            };
        }
    }

On an ASPX page, I have:

<h2><%= showMe.val1 %></h2>

and with this image you can see that on my aspx page it really knows about the properties inside the dynamic object.

Debugger on aspx page showing the contents of showMe

Does anyone know a way to reference the properties of anonymous objects through inline code, or is it simply not possible in the type system? Thank.

+3
source share
1 answer

Direct answer

, Annonymous , . Aspx , , , , , . - ExpandoObject .

public dynamic showMe
    {
        get
        {
            dynamic exp = new ExpandoObject();
                exp.val1 = 5,
                exp.val2 = "This is val2",
                exp.val3 = new List<int>(){1,2,3,4,5}
            return exp;
        }
    }

, , ImpromptuInterface, , . , dlr , .

interface IMyInterface{
    int val1 {get;}
    string val2 {get;}
    IList<int>val3 {get;}
}

public IMyInterface showMe
    {
        get
        {
            return new
            {
                val1 = 5,
                val2 = "This is val2",
                val3 = new List<int>(){1,2,3,4,5}
            }.ActLike<IMyInterface>();
        }
    }
+2

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


All Articles