【问题标题】:How to get 'ReadOnly' or 'WriteOnly' properties from a class?如何从类中获取“ReadOnly”或“WriteOnly”属性?
【发布时间】:2013-03-04 13:52:39
【问题描述】:

我需要从 MyClass 中获取属性列表,不包括“只读”属性,我可以获取它们吗?

public class MyClass
{
   public string Name { get; set; }
   public int Tracks { get; set; }
   public int Count { get; }
   public DateTime SomeDate { set; }
}

public class AnotherClass
{
    public void Some()
    {
        MyClass c = new MyClass();

        PropertyInfo[] myProperties = c.GetType().
                                      GetProperties(BindingFlags.Public |
                                                    BindingFlags.SetProperty |
                                                    BindingFlags.Instance);
        // what combination of flags should I use to get 'readonly' (or 'writeonly')
        // properties?
    }
}

最后,我能把它们排序吗?我知道添加 OrderBy,但是怎么做呢?我只是在使用扩展。 提前致谢。

【问题讨论】:

  • PropertyInfo 上有几个属性表明可读/写能力
  • myProperties.IsReadOnly 是 PropertyInfo[] 属性之一
  • 仅供参考:BindingFlags.SetProperty 在这种情况下不会做任何事情。

标签: c# reflection properties readonly writeonly


【解决方案1】:

您不能使用 BindingFlags 来指定只读或只写属性,但可以枚举返回的属性,然后测试 PropertyInfo 的 CanRead 和 CanWrite 属性,如下所示:

PropertyInfo[] myProperties = c.GetType().GetProperties(BindingFlags.Public |
                                                    BindingFlags.SetProperty |
                                                    BindingFlags.Instance);

foreach (PropertyInfo item in myProperties)
{
    if (item.CanRead)
        Console.Write("Can read");

    if (item.CanWrite)
        Console.Write("Can write");
}

【讨论】:

  • 抱歉,我忘记了排序请求 - 您希望它们如何排序?通过读\写、只读、只写,还是按名称等?
  • 如果你能举出你所说的例子,我将非常感激。
  • 我现在明白了,PropertyInfo[] ... .Where(p => p.CanWrite).OrderBy(x => x.Name).ToArray();
  • 在这种情况下包含BindingFlags.SetProperty 没有用,是吗?除此之外,GetProperties().Where(p => p.CanWrite) 或者 Where(p => p.CanRead && p.CanWrite) 是一个很好的解决方案。
猜你喜欢
  • 2010-09-24
  • 2012-11-08
  • 2011-07-12
  • 2013-07-11
  • 1970-01-01
  • 2014-07-20
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多