具有动态命名参数的扩展方法

NoL*_*ing 2 c# string extension-methods

我正在写一个扩展来用my -function 替换普通函数.string.FormatFormatNamed

到目前为止,我已经有了这段代码,但我想改变输入参数的方式

void Main()
{
    string sql = "SELECT {fields} FROM {table} WHERE {query}"
        .FormatNamed(new { fields = "test", table = "testTable", query = "1 = 1" });
    Console.WriteLine(sql);
}

public static class StringExtensions
{
    public static string FormatNamed(this string formatString, dynamic parameters)
    {
        var t = parameters.GetType();
        var tmpVal = formatString;
        foreach(var p in t.GetProperties())
        {
            tmpVal = tmpVal.Replace("{" + p.Name + "}", p.GetValue(parameters));
        }
        return tmpVal;
    }
}
Run Code Online (Sandbox Code Playgroud)

不是最漂亮的替换,但它完成了这项工作.

无论如何.我想改变所以我可以执行它

.FormatName(field: "test", table: "testTable", query: "1 = 1");
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?我试过谷歌搜索动态命名参数没有好结果.

p.s*_*w.g 5

您将无法指定任意数量的动态命名参数.这不是C#支持的东西.您现有的代码对我来说似乎没问题,虽然我认为不需要dynamic参数.这也可以:

public static string FormatNamed(this string formatString, object parameters)
{
    var t = parameters.GetType();
    var tmpVal = formatString;
    foreach(var p in t.GetProperties())
    {
        tmpVal = tmpVal.Replace("{" + p.Name + "}", p.GetValue(parameters));
    }
    return tmpVal;
}
Run Code Online (Sandbox Code Playgroud)

然后将其称为:

string sql = "SELECT {fields} FROM {table} WHERE {query}"
    .FormatNamed(new { fields = "test", table = "testTable", query = "1 = 1" });
Run Code Online (Sandbox Code Playgroud)

虽然我真的不建议使用这种方法来构造SQL(它根本不会让你免于SQL注入攻击),但这种方法本身是合理的.