开发者

How can I fill an objects attributes in a loop

开发者 https://www.devze.com 2022-12-31 09:52 出处:网络
Imagine, there is a class object, like a Customer Class object, and it has many properties... And I have an array which has its data in a sequence.

Imagine, there is a class object, like a Customer Class object, and it has many properties... And I have an array which has its data in a sequence.

I want to call a property in order the data has been given to the loop; PS: the code below just a presentation and I don't bet it is totally correct. regards. bk e.g;

开发者_运维技巧 foreach(FormValueData item in formValues){

          kkRow."AccountNumber" = item.AccountNumber

        }


If you want to loop through the properties on an object you can do this using reflection. Below is an extension method i wrote for copying the properties of an instance of one class to another instance aof the same class, it might not be exactly what you want to do but you should be able to modify it for your purposes

public static TEntity CopyTo<TEntity>(this TEntity OriginalEntity, TEntity NewEntity)
    {
        PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();

        foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))
        {
            if (CurrentProperty.GetValue(NewEntity, null) != null)
            {
                CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null);
            }
        }

        return OriginalEntity;
    }


You can use the GetMembers method on the type to get out the members:

http://msdn.microsoft.com/en-us/library/xdtchs6z.aspx

You can then invoke the method.

Here's a blog post that discusses this and has a sample:

http://www.dijksterhuis.org/exploring-reflection/

Edit: Ben's answer is better (at least if it's all properties) but I'll leave mine here in case the info is useful.

0

精彩评论

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