我想实现一种“如果返回”/“如果返回值”的功能,没有else语句,因为我只想在条件成立时返回或返回一个值。
我知道,有if (condition) return;
或if (condition) return value;
但我想让代码更简洁。由于其更易读,所以使用这种语法也很好。
我听说使用Roslyn可以实现这个功能,并在这里阅读了问题及其答案:Is there a way to implement custom language features in C#? 但我不知道如何实现它。
所以代码应该是这样的:
public class Testclass
{
public static void Main(String[] args)
{
Testclass t = new Testclass();
t.TestMyClassWithVoid();
bool success = t.TestMyClassWithInt(3) == 3;
bool fail = t.TestMyClassWithInt(2) == 2;
}
public void TestMyClassWithVoid()
{
int value = GetValueFromSomeWhere();
return if value == 3;
DoSomeOtherStuffSinceValueIsNotThree();
}
public int TestMyClassWithInt(int value)
{
return value if value == 3;
DoSomeOtherStuffSinceValueIsNotThree();
return -1;
}
}
你有什么想法可以解决这个问题吗?我开始尝试使用Roslyn.Compilers.CSharp
命名空间,但我不知道如何开始实现。
if(value == 3) return;
但是反过来。 - Matthias Burgerif(value == 3) return;
语法 - 比在C#中使用goto
更高效且更美观。 - Matthias Burger