简体   繁体   中英

Add property to dynamic object .NET

I probably want too much, but my scenario is

public dynamic CreateConfigObject(JobConfigurationModel config) {
    dynamic configObject = new { };

    configObject.Git = new GitCheckout {
        Repository = config.Github.Url
    };

    return configObject;
}

Of course, it fails on configObject.Git since this property does not exist. I want to be able to add any number of properties at run time, with out any beforehand knowledge of number and names of properties;

Is such case possible in C# at all, or my ill JavaScript imagination starts to hurt me? :)

dynamic allows loosely-typed access to strongly-typed objects.

You should use the ExpandoObject class, which allows loosely-typed access to an internal dictionary:

dynamic configObject = new ExpandoObject();

configObject.Git = new GitCheckout {
    Repository = config.Github.Url
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM