创建接口的匿名实例

时间:2016-08-22 19:58:08

标签: vb.net interface anonymous-class

我是vb.net的新手,并且有一个带有类型接口的函数,我想创建一个接口的匿名实例作为方法参数。

接口

Public Interface MessageHandler(Of T)

    Sub Handle(Message As T)

End Interface

我不确定我是否正确描述了我的问题所以这就是我想要的Java:

接口

public interface MessageHandler<T> {

    public abstract void handle(T message);

}

方法调用

function(new MessageHandler<Type>() {

    public void handle(Type message) {
        //Do Something
    }

});

1 个答案:

答案 0 :(得分:2)

您无法在.NET中创建接口的匿名实现。你必须有一个具体的实现,但是你可以隐藏它,并且很容易给出相同类型的匿名化。

我已经用.NET命名了你的命名约定,但现在是:

Public Interface IMessageHandler(Of T)
    Sub Handle(message As T)
End Interface

Public NotInheritable Class MessageHandler
    Private Sub New()
    End Sub
    Private Class AnonymousMessageHandler(Of T)
        Implements IMessageHandler(Of T)
        Private _handler As Action(Of T)
        Public Sub New(handler As Action(Of T))
            _handler = handler
        End Sub
        Public Sub Handle(message As T) Implements IMessageHandler(Of T).Handle
            Dim h = _handler
            If h IsNot Nothing Then
                h(message)
            End If
        End Sub
    End Class

    Public Shared Function Create(Of T)(handler As Action(Of T)) As IMessageHandler(Of T)
        Return New AnonymousMessageHandler(Of T)(handler)
    End Function
End Class

或者,在C#中:

public interface IMessageHandler<T>
{
    void Handle(T message);
}

public static class MessageHandler
{
    private class AnonymousMessageHandler<T> : IMessageHandler<T>
    {
        private Action<T> _handler;
        public AnonymousMessageHandler(Action<T> handler)
        {
            _handler = handler;
        }
        public void Handle(T message)
        {
            _handler?.Invoke(message);
        }
    }

    public static IMessageHandler<T> Create<T>(Action<T> handler)
    {
        return new AnonymousMessageHandler<T>(handler);
    }
}

您可以这样调用它(在VB.NET中):

MessageHandler.Create(Of Integer)(Sub (x) Console.WriteLine(x)).Handle(42)