简体   繁体   中英

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#. 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).

You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious.

You can create a class that wraps an Action and implements that interface:

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.

That is pretty common in java but there is no way you can do it in 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.

Look for the "ImpromptuInterface" NuGet package. With the combination of this package and ExpandoObject, you can do something like this

//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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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