jon jon - 3 months ago 20
C# Question

how to get class property

I have this method for convert object to collection.
I pass class as parameter object into this method

private NameValueCollection ObjectToCollection(object objects)
{
NameValueCollection parameter = new NameValueCollection();

Type type = objects.GetType();

PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
parameter.Add(property.Name.ToString(), property.GetValue(objects, null).ToString());
}

return parameter;
}


in this line

PropertyInfo[] properties = type.GetProperties();


I get each public property such as

{System.Web.Mvc.Async.AsyncManager AsyncManager}
{System.Web.Mvc.IActionInvoker ActionInvoker}
{System.Web.HttpContextBase HttpContext}
.
.
.


I want just get property that I have written, no

{System.Web.Mvc.Async.AsyncManager AsyncManager}
{System.Web.Mvc.IActionInvoker ActionInvoker}
{System.Web.HttpContextBase HttpContext}
.
.
.


How can I do it?

Answer

If you only want properties from the current type, i.e. not from base classes, do the following:

PropertyInfo[] properties = type.GetProperties( BindingFlags.Instance |
                                                BindingFlags.DeclaredOnly |
                                                BindingFlags.Public );

But, to get some additional flexibility, I would suggest using attributes to mark the properties you wish to include:

class Foo
{
    [Serializable]
    public string WeWantThis { get; set; }

    public string ButNotThis { get; set; }
}

Then, for each PropertyInfo, check whether it has that attribute applied to it or not with PropertyInfo.GetCustomAttributes. I used the built-in SerializableAttribute as an example, but you can of course roll your own attribute instead.

Comments