从数据库读取含冒号的值到Model时触发CS0726错误求助
读取含冒号的数据库值时触发CS0726格式说明符错误
我编写了C#代码,尝试将数据库App.Settings表中的数据赋值给ApplicationSettings模型,但读取包含冒号(:)的Value值时触发错误,错误信息如下:
Error: DataTip unavailable = error CS0726: ':' is not a valid format specifier
获取设置的方法
public static void GetApplicationSettings() { Models.Constants.ApplicationSettings obj = new Models.Constants.ApplicationSettings(); var con = Models.Constants.ConnectionString; using (SqlConnection myConnection = new SqlConnection(con)) { string oString = "SELECT [Key] ,[Value] FROM App.Settings"; SqlCommand oCmd = new SqlCommand(oString, myConnection); myConnection.Open(); SqlDataReader rd = oCmd.ExecuteReader(); while (rd.Read()) { PropertyInfo property = obj.GetType().GetProperty(rd["Key"].ToString()); obj.GetType().GetProperty(rd["Key"].ToString()).SetValue(obj, rd["Value"].ToString(), null); } } }
模型类定义
public class ApplicationSettings { public string Secret { get; set; } public string BucketName{ get; set; } }
数据库中Secret对应的Value值包含冒号(例如类似xxxx:xxxx:xxxx的格式)。
解决方法
这个错误并非代码运行时抛出,而是Visual Studio调试器的数据提示(DataTip)解析时的问题——当调试器尝试解析带冒号的字符串时,会误将其当作格式说明符处理。
你可以通过以下方式解决:
- 方法1:禁用数据提示的格式解析
调试时右键点击数据提示,选择“禁用格式说明符”,调试器就不会尝试解析字符串中的格式符号。 - 方法2:代码层面规避调试器误解
将值存入临时变量再赋值,避免调试器直接解析原始字符串,同时优化重复调用GetProperty的冗余操作:while (rd.Read()) { string key = rd["Key"].ToString(); string value = rd["Value"].ToString(); PropertyInfo property = obj.GetType().GetProperty(key); property?.SetValue(obj, value, null); } - 方法3:使用调试器的原始值视图
打开“快速监视”窗口,输入变量名后加上,nq(无引号格式说明符),比如value,nq,就能查看原始的带冒号字符串。
内容的提问来源于stack exchange,提问作者tenzin yeshi
相关产品推荐
相关产品推荐

