Danger of using reflection to add Connection Strin

2019-08-10 19:56发布

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条回答
神经病院院长
2楼-- · 2019-08-10 20:02

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.

查看更多
登录 后发表回答