【发布时间】: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不是任何变量/对象的好名字,它不可读并且在大型项目中会造成很多麻烦。