【问题标题】:C# -> If ... Throw Warning ... Else if... Throw Error.. Else.. ReturnC# -> If ... Throw Warning ... Else if... Throw Error.. Else.. Return
【发布时间】:2015-10-28 03:56:29
【问题描述】:

我在几个网站上查找过,似乎我还没有找到答案 假设我得到了这个结构“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 属性,它也会这样做

任何帮助都会非常有用! :)

【问题讨论】:

  • 您可能可以写一个Roslyn extension 来生成这些错误。您不能在 if-else 语句中执行此操作。
  • 这在 C# 中是不可能的。我知道这不是您期望的答案,但是..
  • 以下代码会发生什么情况(警告、错误或没有这些):MyStruct MS1 = new Random.Next(0, 100); Console.WriteLine((uint)MS1);?
  • 注意:I 不是任何变量/对象的好名字,它不可读并且在大型项目中会造成很多麻烦。

标签: c# warnings main


【解决方案1】:

即使使用 Roslyn 扩展,您也一般无法实现这一点。

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

但是任何其他示例根本无法做到这一点。 MyStruct 值可以来自任何地方,用任何值初始化。没有理由从正在分析的同一方法中的 int 文字进行初始化,因此初始化将对任何分析器隐藏(嗯,任何当前 C# 编译器支持的任何分析器)。

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

从您的问题中不清楚您要解决的更广泛的问题。但无论是什么,你都会以错误的方式去做。我建议您发布一个新问题,清楚准确地解释更广泛的问题是什么,以便您获得一些具体的帮助。

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2017-02-05
    • 2015-10-20
    • 2012-03-05
    • 1970-01-01
    • 2013-09-20
    • 2012-02-29
    • 2012-01-10
    相关资源
    最近更新 更多