gpt4 book ai didi

c# - 使用 roslyn 扩展 C# 语法

转载 作者:太空狗 更新时间:2023-10-29 23:43:55 25 4
gpt4 key购买 nike

我试图在没有 else 情况的情况下实现“return if”/“return value if”,因为我只想在条件有效时返回或返回一个值。

我知道,有 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-命名空间,但我不知道如何开始实现。

最佳答案

如果您可以为此生成正确的 IL,这应该可行。因为这不是新的 CLR 功能,所以您不需要对 dot net core 做任何事情,只需 Roslyn。

要做到这一点,您有两个选择,

一种是让 Roslyn 保持原样,将新语法重写为相应的 C# 语法,然后正常编译。

第二个选项,因为 Roslyn 是开源的,所以可以添加将新语法编译到您自己的 Roslyn 并使用它编译代码的能力。

关于c# - 使用 roslyn 扩展 C# 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38786359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com