简体   繁体   English

如何在SmartFormat反射语法中使用C#扩展方法?

[英]How to use C# extension methods with SmartFormat reflection syntax?

Is it possible to make the following example work with SmartFormat.NET? 是否可以使以下示例与SmartFormat.NET一起使用?

void Main()
{
    Dictionary<string,string> ps = new Dictionary<string, string>();

    ps["Name"] = "Niels";

    Smart.Format("{Name.Foo} is my name", ps).Dump();   
}


public static class Extensions
{

    public static string Foo(this string bar)
    {
        return bar.ToUpper();
    }

}

This will return " is my name" in LinqPad. 这将在LinqPad中返回“是我的名字”。 I want it to return "NIELS is my name". 我希望它返回“ NIELS是我的名字”。 I'm using ToUpper only as a simple example. 我仅使用ToUpper作为简单示例。

Short answer 简短答案

It is currently not possible to call extension methods inside SmartFormat formatting braces. 当前无法SmartFormat格式括号内调用扩展方法

To provide such a feature, SmartFormat would have to look for an extension method of string in all the assemblies of your project, as described in this thread . 为了提供这样的功能, SmartFormat必须在项目的所有程序SmartFormat寻找string的扩展方法,如本线程所述

Example review 范例审查

  • Inside the formatting string 在格式化字符串内

As specified in the project documentation , you can use the ToUpper() method directly inside the format braces , like this (as the method does not take any parameter): 根据项目文档中的指定,您可以像这样在格式括号内直接使用ToUpper()方法 (因为该方法没有任何参数):

Smart.Format("{Name.ToUpper} is my name", ps).Dump();

Maybe the SmartFormat developers should introduce Upper/Lowercase Format Specifiers in the future, as many people are looking for such things. 也许SmartFormat开发人员将来会引入大写/小写格式说明SmartFormat ,因为很多人正在寻找这样的东西。 Nevertheless, it would be quite a challenge for them as ToUpper() and ToLower() calls always seems to be faster than any other implementation or syntactic sugar. 但是,对他们来说这将是一个很大的挑战,因为ToUpper()ToLower()调用总是看起来比任何其他实现或语法糖都快。

  • Outside the formatting string 格式字符串之外

Another way to do it would be to call the extension method outside of your formatting string , but then you lose the Reflection Syntax advantages... 另一种方法是在格式设置字符串之外调用扩展方法 ,但随后您将失去反射语法的优势...

Smart.Format("{0} is my name", ps["Name"].Foo()).Dump();

不,它将返回我的名字 ,不能在SmartFormart.NET中调用扩展方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM