使用 roslyn 扩展 c# 语法 [英] extending c# syntax with roslyn

查看:42
本文介绍了使用 roslyn 扩展 c# 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在没有 else 情况的情况下实现return if"/return value if",因为我只想在条件有效时返回或返回一个值.

I'm trying to implement a "return if"/"return value if" without an else case, since I only want to return or return a value if a condition is valid.

我知道,有 if (condition) return;if (condition) return value; 但我想让代码更清晰一点,它会拥有这种语法就好了,因为它更具可读性.

I know, there is the if (condition) return; or if (condition) return value; but I want to have the code a bit cleaner AND it would be nice to have that syntax since it is more readable.

我听说 roslyn 这是可能的,并在此处阅读问题及其答案:有没有办法在 C# 中实现自定义语言功能? 但我不知道如何实现它.

I heard with roslyn this is possible and read the question with its answeres here: Is there a way to implement custom language features in C#? but I have no clue how to implement it.

所以代码应该是这样的:

So the code would be something like this:

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

any idea how I could solve this? I started trying with the Roslyn.Compilers.CSharp-namespace but I have no clue how to start implementing.

推荐答案

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

If you can generate the correct IL for this, this should be work. Because this is not a new CLR capability you don't need do anything with dot net core, just Roslyn.

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

To do that you have two options,

一种是保留 Roslyn 原样,将新语法重写为相应的 C# 语法,然后按常规进行编译.

One is to leave Roslyn as is and rewrite your new syntax to the correspond C# syntax and then compile as regular.

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

Second option, because Roslyn is an open source, is to add the ability to compile you new syntax to your own Roslyn and compile your code with it.

这篇关于使用 roslyn 扩展 c# 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆