当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: