[英]can we write own language constructs in C#?
i'd like to know if it is possible to implement own language constructs (like lock or foreach) in C#? 我想知道是否可以在C#中实现自己的语言结构(如lock或foreach)?
The idea behind is that i want to mark start and end of a block of operations. 背后的想法是我想标记一个操作块的开始和结束。 instead of writing 而不是写作
startblock("blockname");
blabla();
andsoon();
endblock();
i'd like to write something like 我想写点类似的东西
block("blockname"){
blabla();
test();
}
thank you! 谢谢!
No you can't. 不,你不能。 But there is kind of workaround using IDisposable
. 但是使用IDisposable
有一种解决方法。 You can create a class which will represent block start in constructor and block end in Dispose
. 您可以在Dispose
创建一个表示构造函数和块结尾的块启动的类。 Then you wrap the code into using
. 然后将代码包装成using
。 More here: 更多信息:
Another option is passing a function to a handler. 另一种选择是将函数传递给处理程序。
private void block(string name, Action action)
{
startblock(name);
action();
endblock();
}
Followed by: 其次是:
block("blockname", () =>
{
blabla();
test();
});
Keep in mind, this may be an indication that you need an abstract class (or a regular base class), and allow overriding of that method. 请记住,这可能表示您需要抽象类 (或常规基类),并允许覆盖该方法。
For which purpose do you need it? 你需要它的目的是什么? Just for clarity of writing and clean code? 只是为了清晰的写作和清洁代码? C# is not extensible language. C#不是可扩展的语言。 With using you can achieve that nicely: 通过使用,您可以很好地实现:
using (new Context("block name"))
{
// do your staff here
}
class Context : IDisposable
{
public Context(string name)
{
// init context
}
public void Dispose()
{
// finish work in context
}
}
Nemerle provides constructs like this. Nemerle提供这样的结构。 It is not too dissimilar from C#. 它与C#并没有太大的不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.