How to write a method like string.Format with intellisense support

天涯浪子 提交于 2019-12-01 05:14:24

You cannot make Visual Studio analyze parameter content for you - it simply verifies that code is compilable, and String.Format is compilable even if you haven't specified parameters for all placeholders. But you can use Visual Studio add-in (e.g. ReSharper or CodeRush) which analyzes placeholders count for String.Format formatting string and verifies parameters count passed to this method.

BTW I'm not using ReSharper but looks like it has support for marking any method as string formatting method - Defining Custom String Formatting Methods. You just should annotate your method with StringFormatMethodAttribute attribute:

[StringFormatMethod("formatStr")]
public string MyStringFomratter(string formatStr, params object[] arguments)
{
    // Do some checking and apply some logic
    return string.Format(formatStr, arguments);
}

The compiler doesn't issue a warning for String.Format with wrong number of parameters. However, if you want intellisense support, precede your method with /// and it will create a template for documenting the method. Fill in the documentation and it will appear in the intellisense when you use the method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!