Is there a reason not to use one time objects over explicitly declared ones
Lately I have been spending a lot of time ensuring that my objects all had names that would allow easy identification of their meaning. I have also discovered that you can use objects in a one time fashion like so:
_ProfileList = (New RegistryManager).GetAllProfiles()
As opposed to creat开发者_如何学Cing a named object.
Is there a reason not to do this when all you want is one time access to an object? If anyone knows the pro's and cons that would be great.
PS: It is VB.NET code but either it or C# will be fine if providing examples
That is explicit - it just isn't stored in a variable (indeed, the object never has a "name" - only local variables/fields have names). If you don't need the object more than once, and it doesn't make the core more complicated, then there is no real disadvantage to this. Note that if the object is IDisposable
or similar, you will want a local, i.e.
using(var manager = new RegistryManager()) {
_ProfileList = manager.GetAllProfiles();
}
but other than that, it doesn't care. Indeed, if you do assign to a local and use it right away, I would expect any "release" build to remove the variable completely anyway, meaning that once compiled (in release)
var manager = new RegistryManager();
_ProfileList = manager .GetAllProfiles();
and
_ProfileList = (new RegistryManager()).GetAllProfiles();
are identical (my expectation).
Objects don't have names - variables do.
It's absolutely fine to create an object and use it solely within another expression - although I'd argue that something like a RegistryManager
sounds like it should be a dependency passed in, and not something created within the code like this. It'll make testing harder.
A better example of where this is fine would be StringBuilder
:
string text = new StringBuilder().Append("Foo")
.Append(name)
.DoOtherAppending()
.ToString();
精彩评论