如何在使用GetProperties方法时排除静态属性

时间:2012-11-23 01:34:41

标签: c# reflection properties static bindingflags

当我使用GetProperties()提取特定类的所有属性时,我很想知道是否可以排除静态属性。我知道使用BindingFlags来过滤我需要的属性,但我真正想要的是我想要排除静态属性。我尝试使用这样的东西:

typeof(<class>).GetProperties(!BindingFlags.Static);

但我认为它不起作用,因为VS给我一些语法错误。这是我班级内有属性的内容。

public class HospitalUploadDtl : Base.Tables
        {
            public HospitalUploadDtl() { }
            public HospitalUploadDtl(SqlDataReader reader)
            {
                ReadReader(reader);
            }
            #region Properties
            public long BatchDtlId { get; set; }
            public long BatchNumber { get; set; }
            public string HospitalCode { get; set; }
            public string HospitalName { get; set; }
            public string Address { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
            public string ContractPerson { get; set; }
            public string ContactNo { get; set; }
            public string Email { get; set; }
            public bool isAccredited { get; set; }
            public bool isClinic { get; set; }
            public string FaxNo { get; set; }
            public string TypeofFacility { get; set; }
            public string Category { get; set; }
            public string Specialty { get; set; }
            public string ProviderName { get; set; }
            public bool CashlessInPatient { get; set; }
            public bool CashlessOutPatient { get; set; }
            #endregion

            public static dcHospitalUploadDtl dataCtrl;
            public static dcHospitalUploadDtl DataCtrl
            {
                get
                {
                    if (dataCtrl == null)
                        dataCtrl = new dcHospitalUploadDtl();
                    return dataCtrl;
                }
            }
        }

对于这种情况,我想在调用GetProperties()时排除“DataCtrl”属性。谢谢你的回复。 :)

3 个答案:

答案 0 :(得分:5)

我认为您正在寻找BindingFlags.Instance | BindingFlags.Public(如果您只包含Instance,则不会找到任何属性,因为未指定PublicNonPublic

答案 1 :(得分:1)

电话

typeof(<class>).GetProperties(!BindingFlags.Static);

没有达到您的预期:传递给GetProperties的值是位掩码,而不是表达式。表达式中只允许按位OR。换句话说,你不能说出你不想要的东西:你必须说出你想要的东西。因此,您应该通过!BindingFlags.Static而不是传递BindingFlags.Instance

或者,您可以获取所有属性,然后应用LINQ及其丰富的过滤语义来删除您不需要的项目:

typeof(<class>).GetProperties().Where(p => !p.GetGetMethod().IsStatic).ToArray();

答案 2 :(得分:0)

您应该使用BindingFlags.Instance标志。

typeof(HospitalUploadDtl).GetProperties(BindingFlags.Instance | BindingFlags.Public);