我需要从 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/