简体   繁体   English

创建实现接口的匿名类

[英]Create anonymous class that implements an interface

I am wondering if there is some inline short way of creating a class implementing a interface. 我想知道是否有一些内联的简短方法来创建实现接口的类。 Just like there are the anonymous methods but with implementing interfaces. 就像有匿名方法一样,但是具有实现接口。

The problem is: 问题是:

interface iSomeInterface
{
  void DoIt();
}

public void myMethod(iSomeInterface param)
{
 ...
}

And I would like to use it like this: 我想这样使用它:

object.myMethod(new { override DoIt() { Console.WriteLine("yay"); } } : iSomeInterface);

Any ideas? 有任何想法吗?

Sorry in case its a duplicate. 抱歉,如果它是重复的。

Sorry, no inline implementation of classes in C#. 抱歉,C#中没有内联类的实现。 There are only Anonymous Types , but they don't support adding interfaces (see for example Can a C# anonymous class implement an interface? ) (nor they support adding methods or fields... They only support properties). 只有匿名类型 ,但是它们不支持添加接口(例如,请参见C#匿名类可以实现接口吗? )(它们也不支持添加方法或字段...它们仅支持属性)。

You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious. 您可以使用System.Reflection.Emit的方法在运行时生成类,但是它很长且很繁琐。

You can create a class that wraps an Action and implements that interface: 您可以创建一个包装Action并实现该接口的类:

public sealed class SomeAction : ISomeInterface
{
    Action action;
    public SomeAction (Action action) { this.action = action; }
    public void DoIt() { this.action(); }
}

This allows you to use it as follows: 这使您可以按以下方式使用它:

object.myMethod(new SomeAction(() => Console.WriteLine("yay"));

This is of course only very practical if you are going to reuse SomeAction , but this is probably the most convenient solution. 如果您要重用SomeAction ,那么这当然仅是非常实用的SomeAction ,但这可能是最方便的解决方案。

That is pretty common in java but there is no way you can do it in C#. 这在Java中非常普遍,但是您无法在C#中做到这一点。 You can pass a functions or procedures as parameters though: 您可以通过以下方式将函数或过程作为参数传递:

public void myMethod(Action act)
{
    act();
}

myMethod( () => Console.WriteLine("yay") );

Several (generic) version of Action (procedure with parameters and no return value) and Func (functions with parameters and return value) exist. 存在Action(带参数且无返回值的过程)和Func(带参数且有返回值的函数)的几种(通用)版本。

Look for the "ImpromptuInterface" NuGet package. 查找“ ImpromptuInterface” NuGet程序包。 With the combination of this package and ExpandoObject, you can do something like this 结合使用此包和ExpandoObject,您可以执行以下操作

//Create an expando object and create & assign values to all the fields that exists in your interface
dynamic sigObj = new ExpandoObject();
sigObj.EmployeeKey = 1234;

//Create the object using "ActLike" method of the Impromptu class
INewSignatureAcquired sig = Impromptu.ActLike<INewSignatureAcquired>(sigObj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM