How do I convert a string into a variable reference?
I have to add a lo开发者_如何学编程t of shared folders from a configuration file. the names are very long, but all ends in "Name", "Domain", "Username" and "Password".
An example is:
AddSharedFolder(
myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryName,
myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryDomain,
myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryUsername,
myConfigurationHandler.MyConfiguration.MyService.RSController.repositoryPassword);
My idea was to call it like
AddSharedFolder(
"myConfigurationHandler.MyConfiguration.MyService.RSController.repository");
Then have an overloaded AddSharedFolders method:
private static void AddSharedFolder(string prefix)
{
AddSharedFolder(prefix + "Name", prefix + "Domain", prefix + "Username", prefix + "Password");
}
Obviously the last method is wrong. But how do I convert the string into a variable name? Or is this a really dumb programming practice?
There is no way in C# to do Eval("..."), the language is not that dynamic. Hence your last attempt at a method will not work.
I'd go for
var ctr = myConfigurationHandler.MyConfiguration.MyService.RSController;
AddSharedFolder(ctr.repositoryName, ctr.repositoryDomain,
ctr.repositoryUsername, ctr.repositoryPassword);
Alternatively, you could use strings for the paths, but that would really be going down the wrong lane..
You could use reflection and poke around with, but it is really bad programming practice in this case.
Wrap your settings in something that is easier to handle and accept the long names within that class, if you don't want to work with these long names.
wouldn't it be easier (and not sacrifice type safety) to do something like:
var controller = myConfigurationHandler.MyConfiguration.MyService.RSController;
AddSharedFolder( controller.repositoryName, controller.repositoryDomain, controller.repositoryUsername, controller.repositoryPassword);
That's not the right way to do it. The right way would be to introduce a variable for the type the Properties are defined in. Something like this:
var controller = myConfigurationHandler.MyConfiguration.MyService.RSController;
AddSharedFolder(
controller.repositoryName,
controller.repositoryDomain,
controller.repositoryUsername,
controller.repositoryPassword);
精彩评论