.NET getting and setting RegistryKey values directly in property
I'm getting and setting a registrykey's value directly in a property. The key is opened on pr开发者_C百科ogram 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?
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.
精彩评论