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#?
The idea behind is that i want to mark start and end of a block 开发者_如何学Goof 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
. You can create a class which will represent block start in constructor and block end in Dispose
. Then you wrap the code into using
. More here:
- http://blog.functionalfun.net/2008/05/misusing-idisposable-beyond-resource.html
- http://scottbilas.com/blog/bracketing-operations-with-idisposable/
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. 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. It is not too dissimilar from C#.
精彩评论