开发者

Dynamic Object .NET

开发者 https://www.devze.com 2023-02-01 00:45 出处:网络
I am facing an interesting problem right now. I know it is not that pretty but I have to cope with it anyway.

I am facing an interesting problem right now. I know it is not that pretty but I have to cope with it anyway.

I am calling a webservice that returns (array of string) something like that (by index)

0 - Table Name ("Employees")

1 - List of all fields returned ("Id, Name, Birthdate")

2 - First field value ("1")

3 - Second field value ("Bobby")

4 - Third field value ("1970-01-01")

What I would like to accomplish is to create a object name after the 开发者_JAVA百科index 0, having all the strings in the index 1 being all the properties and feed them with their proper value.

What would be the best way to accomplish this? I have started reading about the ExpandoObject but before going too far I would like to hear your take on this.

Regards

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.


It depends on your use-case but I doubt that dynamic is the way to go here. I would just have a name-value collection like so:

class Result {
    Dictionary<string, string> values = new Dictionary<string, string>();
    public string this[string name] {
        get {
            return this.values[name];
        }
        set {
            this.values[name] = value;
        }
    }

    // some details
}

Then you can populate the values from the webservice and query the values by saying

Result result = PopulateResultFromWebservice();
string id = result["Id"];

etc. If you knew the types you could make this indexer of type object instead and parse the values to their appropriate type and store them as those typed objects.

The issue with dynamic is that if the names of the fields are an unknown, how are you possibly going to write code that utilizes those fields?

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.

Dude, name-value collection all day every day.


If you recive always different kinds of objects with non-predictable set of fields that using ExpandoObject is a good idea (Take a look on Clay library in this case). In other case you just need to create some types that reflects the structure of your object and then materialize them.

Obviously you can use just a simple dictionary, but Using Dynamic object can give you more power, you decide. Real usage case will allow me to give you a better help.

0

精彩评论

暂无评论...
验证码 换一张
取 消