TypeDescriptor.GetProperties(thisType) 返回属性,这些属性是只写的
我试图从类型中获取所有属性,但使用 TypeDescriptor.GetProperties(thisType) 只会为我提供具有 setter 和 getter 的属性。 我有只写属性。 有没有办法检索包括这些在内的 PropertyDescriptorCollection?
/阿斯格
I'm trying to get all properties from a type, but using TypeDescriptor.GetProperties(thisType) will only supply me with properties, that has both setter and a getter. I have write-only properties. Are there a way to retrieve a PropertyDescriptorCollection including those?
/Asger
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只写属性是一种罕见的野兽,并且不存在于 System.ComponentModel / PropertyDescriptor 空间中。
PropertyDescriptor
被设计为可读的。 我可能可以破解HyperDescriptor
来填充只写属性,但这将是一个黑客 - 并且它可能必须抛出get
异常,这可能会影响调用代码一点点。作为旁白; 我通常建议不要使用只写属性; 人们抛出的教科书示例是密码(
public string Password {private get;set;}
) - 我宁愿有一个void SetPassword(string newPassword)
方法...你真正想做的是什么? 这里有一系列选项,都非常容易实现:
Delegate.CreateDelegate
(非常简单)Expression.Compile
( 有点困难,但不多)Reflection.Emit
(相当困难)PropertyDescriptor
(相当困难)如果您让我知道您真正想做的事情(而不是您当前尝试做的方式),我也许可以提供更多帮助。
作为使用
Delegate.CreateDelegate
的示例(请注意,您可能希望将委托存储在某处并多次重复使用它):编辑以显示如果您不知道如何执行此操作运行时的特定类型
或者使用
Expression
API (.NET 3.5):Write-only properties are a rare beast, and don't exist in the System.ComponentModel / PropertyDescriptor space.
PropertyDescriptor
s are designed to be readable. I could probably hackHyperDescriptor
to shim write-only properties, but it would be a hack - and it would presumably have to throw exceptions forget
, which could impact calling code quite a bit.As an aside; I generally advise against write-only properties; the text-book example that people trot out is passwords (
public string Password {private get;set;}
) - I'd much rather have avoid SetPassword(string newPassword)
method...What is it that you actually want to do? There are a range of options here, all very achievable:
Delegate.CreateDelegate
(very easy)Expression.Compile
(a little harder, but not much)Reflection.Emit
(quite hard)PropertyDescriptor
(quite hard)If you let me know what you actually want to do (rather than the way you are currently trying to do it), I might be able to help more.
As an example using
Delegate.CreateDelegate
(note you would want to stash the delegate somewhere and re-use it lots of times):edited to show how to do it if you don't know the specific types at runtime
Or alternatively using the
Expression
API (.NET 3.5):使用
System.Type.GetProperties()
相反,它返回所有属性。 请注意,这会返回PropertyInfo[]
而不是PropertyDescriptorCollection
。Use
System.Type.GetProperties()
instead, that returns all properties. Notice that this returns aPropertyInfo[]
instead of aPropertyDescriptorCollection
.