c# - 如何从类中获取 'ReadOnly' 或 'WriteOnly' 属性?

标签 c# reflection properties readonly writeonly

我需要从 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<>,但是如何?我只是在使用扩展。 提前致谢。

最佳答案

您不能使用 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");
}

关于c# - 如何从类中获取 'ReadOnly' 或 'WriteOnly' 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15439363/

相关文章:

c# - 通过属性重新分配结构的成员变量

c# - 只读的属性,但只能在类之外

c# - 在 C# 中,我可以为自动实现的属性访问器创建委托(delegate)实例吗?

c# - 旋转 IEnumerable 列表

c# - 能否导出C#接口(interface)定义 'override'函数定义?

c# - 如何将 C# Select () 扩展委托(delegate)或表达式传递给存储库?

java - 通过 Java 反射重新创建(通用)成员并填充/分配字段成员

c# - 通过其 Skype4COM.dll COM API 控制 Skype

c# - 将 Razor C# 与 javascript 结合使用

C# - GetValue - 对象与目标类型不匹配