Uncomment code programmatically

柔情痞子 提交于 2019-12-23 04:33:05

问题


How can I comment out some comment programmatically? Think of something like this:-

void releaseA()
{
   //ToDo:
}
//string A = "Test";
releaseA();
textbox1.Text = A;

How can I achieve this and implement method releaseA to comment out //string A = "Test"; I searched but still can't find anything.


回答1:


I think what you really want to do is this:

string a = "";

if (condition)
    a = "Test";

textBox1.Text = a;

So for your example of a checkbox and a text box:

string text = "";

if (checkBox.Checked)
    text = inputTextBox.Text;

resultTextBox.Text = text;



回答2:


If you want to comment code before a build of the specified file you can work with compiler switches and specify the compiler switch when building the file in VS or with MSBuild.

You can use something like this:

#ifdef _DEBUG
//string A = "Test";
#else
string A = "Test";
#endif



回答3:


I believe that comments are ignored by the compiler and won't be resident in the overall exe. So this would technically be impossible, given your current code.

Besides, you'd have no reference to which 'line' said code would be on once its compiled to bytecode.




回答4:


I don't code in c#, but do a bit in c & Objective C, so i am sure this approach is portable.

if i have a feature i want to be able to conditionally enable at compile time, and potentially disable it at runtime (not the other way around!), i use the following approach.

In a global (prefix) header that all relevant files will see (or a command line switch), define a constant that forces the compiler to physically include the feature's code into the executable. this is effectively a bool constant.

#define acme_support        1

In a common header file (eg settings.h) define a wrapper around this which tells the runtime code if the feature is available. if it's not available, it's hard coded. if it is available, it's an external bool.

#if acme_support
extern bool runtime_acme_support;
#else
#define runtime_acme_support 0
#endif

in the implementation file associated with "settings.h" (lets call it "settings.c"):

#if acme_support
bool runtime_acme_support = 1;
#endif

Then throughout your project where you want to include code for the feature:

#if acme_support

    if (runtime_acme_support) {

        /*  process the acme widgets for the acme store. */

    }

#endif

As you can see, the #if / #endif prevents disabled code being enabled if it was not included at compile time, but you can still "disable" the feature at runtime if certain conditions require that (for example required hardware is not present)

Note that's an #if not a #ifdef, as #ifdef will still be true since '0' is still "defined", whereas #if is a boolean test on the value '0' / '1' which is false/true respectively.



来源:https://stackoverflow.com/questions/17820466/uncomment-code-programmatically

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