MVC Helper Extension问题

BeC*_*ool 2 c# asp.net asp.net-mvc c-preprocessor

我需要HtmlHelper在我的MVC项目中实现一个扩展,只是为了输出一些字符串,但只能在DEBUG模式下,而不是在RELEASE中.我的第一次尝试是:

[Conditional("DEBUG")]
public static string TestStringForDebugOnly(this HtmlHelper helper, string testString)
{
    return testString;
}
Run Code Online (Sandbox Code Playgroud)

但显然这会产生编译错误:

"条件属性无效,因为它的返回类型不是无效的."

所以我的理解是,一旦你设置了[Conditional]属性,它就不允许返回任何内容?为什么?

还有另一种方法来实现这种功能吗?任何帮助将非常感激.

Joh*_*sch 6

您可以使用预处理器指令:

public static string TestStringForDebugOnly(this HtmlHelper helper, string testString)
{
#if DEBUG
    return "debug";
#else
    return "other";
#endif
}
Run Code Online (Sandbox Code Playgroud)

至于你原来的问题,看看C#规范的第17.4.2节表明:

[A]条件方法必须具有返回类型 void

我只能推测为什么语言的设计者决定了这一点,但我冒昧地猜测它是因为如果条件是C#编译器没有将方法调用编译成IL false,所以实际上它就像你从未调用过方法一样(如果预期返回值,这会在运行时导致一些明显的问题!)