【问题标题】:Why does it get nothing that Getting private Properties? (c#) [closed]为什么获取私有属性一无所获? (c#) [关闭]
【发布时间】:2021-03-17 05:11:42
【问题描述】:
public class A{
    public Info m_Info = new Info();
    Main()
    {
        Console.WriteLine(m_Info.Property_Count());
    }
    public class Info{

        protected int i_Id;
        protected string s_Name; 

        public int Property_Count(){
            System.Reflection.PropertyInfo[] data = this.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            foreach(var item in data)
                Console.WriteLine(item.Name);
            return data.Length;
        }
    }
}

我正在尝试获取私有或受保护的属性~ 但是data.Length总是返回0,听上去好像什么都没有,为什么呢?

【问题讨论】:

标签: c# reflection private protected getproperty


【解决方案1】:

您的班级没有任何properties。这些:

protected int i_Id;
protected string s_Name; 

fields。您可以将它们更改为属性:

protected int i_Id { get; set; }
protected string s_Name { get; set; }

或者你可以使用GetFields:

System.Reflection.FieldInfo[] data = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多