在 C# 中动态实现接口的最佳方法是什么? [英] What is the nicest way to dynamically implement an interface in C#?
问题描述
我经常发现仅仅因为我需要它一次来进行某个方法调用而不得不实现一个接口很让人分心.我必须在其他地方创建一个类,实现接口等等.
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 有一个名为匿名类的特性,它允许实现接口排队".因此,我的问题是:使用现有语法在 C# 中完成类似任务的最好 方式是什么(我意识到最好"是主观的).我正在寻找好的语法,不一定是性能.
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.
我在 C# 中实现了以下 POC:
I implemented the following as POC in C#:
给定
interface IFoobar
{
Boolean Foobar(String s);
}
IFoobar foo = Implement.Interface<IFoobar>(new {
Foobar = new Func<String, Boolean>(s => s == "foobar")
});
这使用匿名对象和一些反射/发射来实现 IFoobar
接口(忽略属性、通用方法和重载).但是,我不喜欢 new Func<...>
的东西,但不能没有.
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.
有没有更好的方法?
编辑:我不是在寻找 Java 与 C# 的火焰战争.
Edit: I'm not looking for Java vs C# flame wars.
推荐答案
您提到您不需要经常这样做,不关心性能,并且通常希望在单元测试期间这样做.为什么不使用模拟框架?
You mentioned that you didn't need to do this often, don't care about performance, and usually want to do it during unit testing. Why not use a mocking framework?
例如,以 Moq 库为例:
public interface IFoobar {
Boolean Foobar(String s);
}
void Main() {
var foo = new Mock<IFoobar>();
foo.Setup(x => x.Foobar(It.IsAny<string>()))
.Returns((string s) => s == "foobar");
foo.Object.Foobar("notbar"); // false
foo.Object.Foobar("foobar"); // true
}
这篇关于在 C# 中动态实现接口的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!