I often find it quite a distraction to have to implement an interface just because I need it once for some method call. I have to create a class somewhere else, implement the interface etc. etc.
Java has a feature called Anonymous Classes that allows one to implement the interface "inline". My question is thus: what is the nicest way you can think of of accomplishing something similar in C# using existing syntax (and I realise that "nicest" is subjective). I'm looking for nice syntax, not necessarily performance.
I implemented the following as POC in C#:
Given
interface IFoobar
{
Boolean Foobar(String s);
}
IFoobar foo = Implement.Interface<IFoobar>(new {
Foobar = new Func<String, Boolean>(s => s == "foobar")
});
This uses an anonymous object and some reflection/emit to implement the IFoobar
interface (overlooking properties, generic methods and overloading). But, I'm not a fan of the new Func<...>
stuff but can't do without.
Looking around I noticed a library called Impromptu Interface, but wasn't impressed by its syntax to support methods.
Is there a "nicer" way?
Edit: I'm not looking for Java vs C# flame wars.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…