检查对象的实例是否是只读的
如果我有一个对象的实例,如何检查它是否是只读的?
我已经搜索过 System.Type,其中有很多 IsXxxx()
和 GetXxxx()
类型的函数,但没有 IsReadOnly()
, IsWriteable()
、GetReadWriteProperty()
或类似的任何内容。我想像 myObj.GetType().IsReadOnly() 这样的东西太简单了,而且 Object 类本身除了 GetType() 之外没有任何用处。
当我用谷歌搜索这个问题时,我得到的只是使用 readonly 关键字的方法。
我想过使用 Reflection 和 GetProperty() 但这是一个存在于 List<> 中的基类,我认为我需要这个对象的实例成为另一个对象中的单独属性才能做到这一点。
有什么想法吗?
If I have an instance of an Object, how do I check whether or not it is read only?
I've scoured through System.Type and that are plenty of IsXxxx()
and GetXxxx()
types of functions but no IsReadOnly()
, IsWriteable()
, GetReadWriteProperty()
, or anything along those lines. I guess something like myObj.GetType().IsReadOnly()
would've been too easy, and the Object class itself has nothing useful in it other than GetType().
When I google this question all I get are ways to use the readonly keyword.
I thought of using Reflection and GetProperty() but this is a base class that exists in a List<>, I would need the instance of this object to be a lone property in another object for me to do this I would think.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不存在只读对象这样的概念。 变量可以是只读的,但这是另一回事。例如:
这里只有一个
StringBuilder
对象,但有两个字段 - 一个只读,一个可写。如果您询问类型是否是不可变的(例如
string
是不可变的,StringBuilder
不是),这是一个更棘手的问题......有许多不同种类的不变性。请参阅 Eric Lippert 关于此事的博客文章了解更多详细信息。There's no such concept as an object being read-only. A variable can be read-only, but that's a different matter. For example:
Here there's only one
StringBuilder
object, but two fields - one read-only and one writable.If you're asking whether a type is immutable (e.g.
string
is immutable,StringBuilder
isn't) that's a thornier question... there are many different kinds of immutability. See Eric Lippert's blog post on the matter for more details.如果要检查只读字段,请使用 FieldInfo 类上的
IsInitOnly
属性http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isinitonly.aspx
If you want to check for ReadOnly fields, Use the
IsInitOnly
property on the FieldInfo classhttp://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isinitonly.aspx
Jon Skeet 是对的(当然),C# 中不存在只读对象这样的东西。但是,某些框架(例如 WPF)有自己的只读对象概念。 WPF 有 freezables,这些对象可以在运行时,您可以通过
IsFrozen
检查可冻结对象是否被冻结。Jon Skeet is right (of course), there is no such thing as a read-only object in C#. However, some framework, such as WPF have their own concept of read-only objects. WPF has freezables, objects which can be made immutable at runtime, you can check whether a freezable is frozen via
IsFrozen
.