如何写这样的String.Format方法与智能感知支持 [英] How to write a method like string.Format with intellisense support

查看:133
本文介绍了如何写这样的String.Format方法与智能感知支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到了格式的String.Format 参数的弗里斯特参数写入的方法。正如你所知道的智能感知是知道的第一个参数的约束和检查其与参数的一致性。我怎么能写这样的方法。

作为一个简单的例子,考虑的String.Format 一包这样的:

 公共字符串MyStringFomratter(字符串formatStr,params对象[]参数)
{
    //做一些检查,并应用一些逻辑
    返回的String.Format(formatStr,参数);
}
 

我怎么能告诉编译器或IDE的 formatStr 是像的String.Format 的第一个参数?

所以,如果我有一些code是这样的:

 变种X = MyStringFormatter(FristName:{0},名字:{1},名字);
//这个code应该产生在IDE的警告
 

解决方案

您不能让Visual Studio的分析为您的参数内容 - 它只是验证code是编译和的String.Format 是编译的,即使你没有指定参数,所有的占位符。但是你可以使用Visual Studio外接(如 ReSharper的或<一href="http://visualstudiogallery.msdn.microsoft.com/b14bb191-2d39-4e82-8bd2-826bf79237a0">$c$cRush)该分析占位符计数的String.Format 格式化字符串,并验证参数计数传递给此方法。

BTW我不使用ReSharper的,但看起来像它具有标识的任何方法,字符串格式化方法的支持 - <一个href="http://www.jetbrains.com/resharper/webhelp/$c$c_Analysis__String_Formatting_Methods.html">Defining自定义字符串格式化方法的。你只应 StringFormatMethodAttribute 注释您的方法属性:

  [StringFormatMethod(formatStr)
公共字符串MyStringFomratter(字符串formatStr,params对象[]参数)
{
    //做一些检查,并应用一些逻辑
    返回的String.Format(formatStr,参数);
}
 

Consider a method to write with a format parameter like string.Format's frist parameter. As you know the Intellisense is aware of first parameter's constraints and checks for its consistency with parameters. How can I write such method.

As a simple example, consider a wrap of string.Format like:

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

How can I say to the compiler or IDE that formatStr is something like string.Format's first parameter?

So if I have some code like this:

var x = MyStringFormatter("FristName: {0}, LastName: {1}", firstName);
// This code should generate a warning in the IDE

解决方案

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);
}

这篇关于如何写这样的String.Format方法与智能感知支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆