如何获得类属性

本文关键字:属性 何获得 | 更新日期: 2023-09-27 18:07:32

我有这个方法将对象转换为集合。我将class作为参数对象传递给这个方法

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;
}

PropertyInfo[] properties = type.GetProperties();
我得到每个公共属性,比如
{System.Web.Mvc.Async.AsyncManager AsyncManager}
{System.Web.Mvc.IActionInvoker ActionInvoker}
{System.Web.HttpContextBase HttpContext}
.
.
.

我只想得到我写的属性,没有

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

我该怎么做?

如何获得类属性

如果您只想要当前类型的属性,即不需要基类的属性,请执行以下操作:

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

但是,为了获得一些额外的灵活性,我建议使用属性来标记您希望包含的属性:

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

然后,对于每个PropertyInfo,使用PropertyInfo.GetCustomAttributes检查它是否应用了该属性。我使用内置的SerializableAttribute作为示例,但您当然可以滚动自己的属性。