简体   繁体   中英

C# : creating an error in struct implicit convertion

i Have a Struct called Bool, it's simply to represent bool values in 1 & 0 (thats not all of the struct, only where my problem is).

public struct Bool
{    
    public static readonly Bool Btrue = 1;
    public static readonly Bool Bfalse = 0;
    int value;

    public Bool(int value)
    {
        this.value = value;
    }
    public static implicit operator Bool(int x)
    {
        if (x == 1) return Btrue;
        else return Bfalse;
    }
}

what i'm trying to reach is in this pic

the kind of error i'm talking about

i want the other line (Bool c = 2) to show me the same kind of error in (int a = 1.2) with a red line (i know that 1.2 isn't an integer, but i'm talking about the error).

i want that if the entered value (Bool c = 2) [I mean the 2], wasn't 1 or 0, an error is shown with a red line under the code.

i know about exceptions, but i want this error to be a compile error rather than an execution error (if possible)

You cannot introduce new compiler errors. My suggestion is to treat 0 as False and all other values as True . This a very common approach used by many programming languages.

You could also use Code Contracts or Use Roslyn to Write a Live Code Analyzer for Your API .

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