- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我需要从 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/
我有以下属性: public virtual String Firstname { get; set; } 我只希望能够写入当前为空(未设置)的字段,这可以通过 DataAnnotations 实现吗
我在 VB.Net 中将此类作为自定义控件的一部分编写。它允许我切换 3 个链接标签的状态,并使用 Text 属性设置每个标签的文本。这就是允许用户使用它做的所有事情。我可以毫无问题地转换 Enabl
我需要从 MyClass 中获取属性列表,不包括“只读”属性,我可以获取它们吗? public class MyClass { public string Name { get; set; }
我在 idl 文件中定义了一个接口(interface),并尝试将 vb6 项目转换为 vb.net。 转换从此 idl 的 tlb 创建了互操作,并且在 vs2010 中它提示该属性未实现(如下所示
我正在阅读 Stroustrup 的 c++ FAQ我注意到,有一次,他在语言中有一个writeonly限定符。经过一番讨论,我和一位同事只能想出一个目的——副作用,特别是在某些内存映射 IO 的情况
我有一个主从数据库。为了平衡一些负载,我希望我所有的 INSERT/UPDATE 查询都转到主服务器,而我所有的 SELECT 查询都转到从服务器(因为你不能在不弄乱它的情况下写入从服务器)。我在 d
我在 .Net 5.0 Web API 中使用 Swashbuckle (6.1.1)。我仍在学习,但我想实现一个类,其中某些属性仅在使用 GET“阅读”时才有效。 , 以及使用 POST“写入”时的
我是一名优秀的程序员,十分优秀!