c#→如果. .抛出警告…其他如果. .抛出错误.其他的事情.回报

本文关键字:其他 如果 回报 错误 警告 出错 | 更新日期: 2023-09-27 18:06:24

我在几个网站上查了一下,似乎我还没有找到答案假设我们有一个结构体MyStruct

public struct MyStruct
{
    private int value;
    private MyStruct(int i)
    {
        value = i;
    }
    public static implicit operator MyStruct(int I)
    {
        return new MyStruct(I);
    }
    public static implicit operator int (MyStruct MS)
    {
        return MS.value;
    }
    public static explicit operator uint (MyStruct I)
    {
        return Convert.ToUInt32(I);
    }
}

我想对显式运算符

if (I< 40) Then it will throw a compiler warning
else if (I > 50) Then it will throw a compiler error
else -> it will return a value

我知道我可以使用抛出异常,但我只想要警告/错误部分所以它会像这样:

public class Program
{
    static void Main()
    {
        MyStruct MS1 = 30;
        MyStruct MS2 = 60;
        Console.WriteLine((uint)MS1);//So it will throw a warning
        Console.WriteLine((uint)MS2);//So it will throw an error
        Console.ReadKey();
    }
}

如果我想做这样的事情:

    public static explicit operator uint (MyStruct I)
    {
        if (I < 40)
        {
             #warning Number must be less than 50 and bigger than 40
        }
        else if (I > 50)
        {
             #error Number must be less than 50 and bigger than 40
        }
        return Convert.ToUInt32(I);
    }

它只是抛出警告和错误,甚至不调用操作符我不能在变量

上使用#If/#Else

如果我使用Obsolete属性,它会做相同的

任何帮助将是非常感激!:)

c#→如果. .抛出警告…其他如果. .抛出错误.其他的事情.回报

即使使用Roslyn扩展,您也不会一般能够实现这一点。

在您展示的示例中,理论上可以这样做(在Roslyn中,它为您提供了编译时钩子),但即使这样,也需要对代码进行一些重要的分析,以识别MyStruct变量的值,因为它们将在运行时调用explicit uint操作符。

但是任何其他的例子根本不能完成这一点。MyStruct值可以来自任何地方,用任何值初始化。没有理由初始化应该发生在被分析的相同方法中的int文字中,因此初始化将对任何分析器隐藏(好吧,任何当前c#编译器支持的任何分析器)。

事实上,变量之所以如此强大的原因之一是它们可以包含任意值,在代码中传递、操纵等等。正是这种能力使得在编译时检测变量在运行时的值变得不切实际。

从你的问题中不清楚你想要解决的更广泛的问题是什么。但不管是什么,你都用错了方法。我建议你发一个新的问题,清楚而准确地解释这个更广泛的问题是什么,这样你就可以得到一些具体的帮助。