简体   繁体   中英

How to prevent a method from accepting 2 false bool in C# .NET?

I have a method with this signature:

public static void DirFillWEx(ComboBox cb, bool dirFill, bool fileFill);

this is put in a dll library I wrote myself. My question is: is there a way to instruct Visual Studio that this method cannot accept both the bool values as false, so I get an error at compile time (NOT RUNTIME!)?

For Example:

DirFillWEx(my_cb, false, true);
DirFillWEx(my_cb, true, true);
DirFillWEx(my_cb, true, false);

but not

DirFillWEx(my_cb, false, false);

Thank you all!

You could define an enum:

enum FillMode
{
  Dir,
  File,
  Both
}

and then type your method to take the enum:

public static void DirFillWEx(ComboBox cb, FillMode fillMode);

No, you're misunderstanding how the compiler works. Your method signature allows for bool values to be passed, you cannot force a compile time check on the values passed, only the types.

You can do a runtime check on either the calling end or inside the method to check the parameters are in a valid state before proceeding.

There is probably some way of re-writing the compiler for your suggested purpose but obviously doing so would be indicative of an issue with your design.

You can do value clamping via enums as suggested by Sean, but this doesn't answer your original question - no, you cannot (easily/feasibly) clamp values passed to a function at compile time in C#.

I don't think you can do that at compile time, but you could do this at the start of your function:

public static void DirFillWEx(ComboBox cb, bool dirFill, bool fileFill)
{
    if(!dirFill && !fileFill)
    {
        return;
    }
}

What you also could do is when you call the function:

if(!dirFill && !fileFill)
{
}
else
{
    DirFillWex(cb, dirFill, fileFill);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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