这段代码使用了 c# 的 字符串插值($) 和 逐字字符串(@) 功能,并在 sql 语句中动态拼接变量。下面详细解释它们的用法:
1.$(字符串插值)
$ 是 c# 的 字符串插值 符号,允许在字符串中直接嵌入表达式(用 {} 包裹),例如:
string name = "alice";
string message = $"hello, {name}!"; // 输出:hello, alice!
在 sql 语句中,$ 用于动态插入变量值,如 {level}、{getnextsortorder(parentid)} 等。
2.@(逐字字符串)
@ 是 c# 的 逐字字符串 符号,它会:
- 忽略转义字符(如
\n、\t等) - 允许字符串跨多行(适合 sql 语句)
- 保留所有空格和换行
例如:
string sql = @"
select *
from users
where id = 1";
如果不加 @,换行符需要用 \n 表示,而加了 @ 后可以直接换行。
3.$@(同时使用)
$@ 结合了两种功能:
- @ 允许 sql 语句跨多行
- $ 允许在字符串中插入变量
所以:
string strsql = $@"
insert into system
(pid, level, sortorder, name, remark, createdtime, modifiedtime)
values (...)
";
这样既保持了 sql 语句的可读性,又能动态插入变量。
4.{(level == 3 ? $"'{editform.target.replace("'", "''")}'" : "null")}解释
这段代码是一个 嵌套的三元运算符 + 字符串插值,用于动态生成 sql 语句中的 remark 字段值:
- level == 3:检查当前节点是否是第 3 级(可能是菜单项)
- 如果是,则:
- editform.remark.replace("'", "''"):对 remark 字符串进行 sql 转义(单引号 ' 替换成 '',防止 sql 注入)
- $"'{...}'":用单引号包裹(因为 sql 字符串需要用 ' 括起来)
- 如果不是(level != 3),则直接插入 null(sql 的 null 值,不加引号)
- 如果是,则:
示例
假设:
level = 3editform.remark= "admin/home"
则生成的 sql 部分:
remark= 'admin/home'
如果 level = 2,则:
remark= null
5. 完整 sql 拼接示例
假设:
- parentid = 1
- level = 3
- editform.nodename = "admin page"
- editform.remark = "admin/home"
生成的 sql 语句:
insert into system
(pid, level, sortorder, name, remark, createdtime, modifiedtime)
values (
1,
3,
1, -- 假设 getnextsortorder(parentid) 返回 1
'admin page',
'admin/home',
getdate(),
getdate()
)
6. 安全性注意事项
虽然这种拼接方式方便,但存在 sql 注入风险(如果 nodename、target 等来自用户输入)。更安全的方式是使用 参数化查询(如 sqlcommand.parameters):
using (var cmd = new sqlcommand(
@"insert into system
(pid, level, sortorder, name, remark, createdtime, modifiedtime)
values (@pid, @level, @sortorder, @name, @remark, getdate(), getdate())",
connection))
{
cmd.parameters.addwithvalue("@pid", parentid ?? (object)dbnull.value);
cmd.parameters.addwithvalue("@level", level);
cmd.parameters.addwithvalue("@sortorder", getnextsortorder(parentid));
cmd.parameters.addwithvalue("@name", editform.nodename);
cmd.parameters.addwithvalue("@remark", level == 3 ? editform.target : (object)dbnull.value);
cmd.executenonquery();
}
这样可以有效防止 sql 注入攻击。
到此这篇关于c#中字符串插值($) 和 逐字字符串(@)的使用的文章就介绍到这了,更多相关c# 字符串插值 和 逐字字符串内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论