.NET 直接在属性中获取和设置RegistryKey值
我直接在属性中获取和设置注册表项的值。该键在程序启动时打开,在退出时关闭。
public bool AlwaysSyncBeforeRun
{
get{ return Convert.ToBoolean(MayaRegistryKey.GetValue("AlwaysSyncBeforeRun")); }
set { MayaRegistryKey.SetValue("AlwaysSyncBeforeRun", value); }
}
此属性不适合频繁使用。
这是个好主意吗?
I'm getting and setting a registrykey's value directly in a property. The key is opened on program startup and closed on exit.
public bool AlwaysSyncBeforeRun
{
get{ return Convert.ToBoolean(MayaRegistryKey.GetValue("AlwaysSyncBeforeRun")); }
set { MayaRegistryKey.SetValue("AlwaysSyncBeforeRun", value); }
}
This property is not meant for frequent usage.
Is this a good idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这不是一个好主意,因为使用您的类的开发人员可能不知道属性内部发生了什么,并且注册表访问具有安全隐患。如果使用您的类的应用程序没有注册表访问权限,则简单地获取该属性将导致异常。
对于这种情况,我最好使用该属性将值存储在内存中,并提供一些 Load() 方法来填充该属性和一个 Save() 方法,只要应用程序准备好保存到注册表,就可以调用该方法。
.NET Framework 设计指南中的此链接可能提供其他上下文:在属性和方法之间进行选择
I don't think it is a good idea as the developer using your class might not be aware of what is happening inside the property and registry access has security implications. If the application using your class do not have registry access permission, then a simple get on the property will cause an exception.
For this scenario I would better use the property to store the values in memory and provide some Load() method to populate the property and a Save() method that can be called whenever the application is ready to save to registry.
This link from the .NET Framework Design Guidelines might provide additional context: Choosing Between Properties and Methods
如果它不适合经常使用,为什么要保持打开状态?
你做类似的事情来提高性能。但是,就您而言,您并不经常使用它。因此,我建议您可以打开密钥,读取/写入值并关闭它。会很安全的。
If it is not meant for frequent usage, why do you keep it open?
You do something like that to improve performance. But, in your case, you don't use it frequently. So, I suggest you could open key, read/write value and close it. It will be safe.
很多人说你的房产根本不应该有功能。
您是否尝试过在程序打开对注册表项的引用时编辑注册表项?我没有尝试过,但如果您的应用程序在运行期间锁定密钥,那么最好读取密钥、存储它并在最后更新它。
Alot of people say you should not have functionality at all in a property.
Have you tried editing the registry key while your program has the reference to it open? I have not tried but if your app is locking the key for the duration its running then it may be better to read the key, store it and update it at the end.