问题
I have seen several post detailing how to get around the ReadOnly barrier in adding connection strings to ConfigurationManager.ConnectionStrings. See an example of one such post below. Along of each of these examples comes a dire, yet vague warning that the technique employed is "dangerous". What is the danger?
Dim cssc As ConnectionStringSettingsCollection = WebConfigurationManager.ConnectionStrings
Dim t As Type = cssc.GetType().BaseType ' System.Configuration.ConfigurationElementCollection
Dim fi As FieldInfo = t.GetField("bReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)
fi.SetValue(cssc, False)
回答1:
One reason this is 'dangerous' is that you are relying on a private field named bReadOnly
. That field is not part of the public .NET API and may change without notice in a future version of .NET. If that happens, and if you upgrade to that version, your code will no longer work.
来源:https://stackoverflow.com/questions/18039710/danger-of-using-reflection-to-add-connection-strings-to-configurationmanager-con