gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:09:32 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com