简体   繁体   English

代码生成器可以使内联抽象类满足C#接口的Java匿名内部类的作用?

[英]Code generator to make inline abstract classes that fulfill the role of java anonymous inner classes for C# interfaces?

Note: I'm aware that C# has anonymous types and inner types, but these fulfill markedly different roles from the java anonymous inner classes of old. 注意:我知道C#具有匿名类型和内部类型,但是它们扮演的角色与旧的Java匿名内部类明显不同。

Suppose I have an interface: 假设我有一个接口:

public interface Foo<T>
{
    int Fizz(string a);
    T Buzz(object o);
    void Crackle();
}

Is there something out there (ReSharper macro or the like) that would allow me to generate an implementing class that would fulfill the role of a java style AIC (ie, allow me to define functionality inline). 是否有东西(ReSharper宏等)可以让我生成一个实现类,该类可以实现Java风格的AIC(即,让我内联定义功能)。 ie

public class FooAIC<T> : Foo<T>
{
    public Func<string, int> Fizz;
    public Func<object, T> Buzz;
    public Action Crackle;

    int Foo<T>.Fizz(string a)
    {
        return Fizz(a);
    }

    T Foo<T>.Buzz(object o)
    {
        return Buzz(o);
    }

    void Foo<T>.Crackle()
    {
        Crackle();
    }
}

(I haven't thought this through in a great amount of detail. So I guess one could create a smarter class with readonly member injection, null checking on invocation, works for abstract classes etc, but this should convey the general idea of what I want to achieve) (我还没有详细的大量以为这通过。所以我想一个可以创建一个有只读成员注射,空检查上调用一个聪明类,适用于抽象类等,但这应该传达什么样的总体思路我想要实现)

Anybody know something which can do this? 有人知道什么可以做到吗? Or, barring that, recommend the most painfree way to look at doing something like this - would this be possible in the T4 engine? 或者,除非如此,否则推荐使用最轻松的方法来观察类似的事情-T4引擎有可能做到这一点吗?

Your solution is ok, tipically in .NET you don't need anonymous classes as most part of the time you only override/implement a method on them, and for that you have delegates (wich i think are a much better choice). 您的解决方案是可以的,通常在.NET中,您不需要匿名类,因为在大多数情况下,您只需要在它们上重写/实现一个方法,因此您可以委派委托(我认为这是一个更好的选择)。 But if you need to override/implement several methods, creating a stub class with delegates for each method is the best way. 但是,如果需要重写/实现几种方法,最好的方法是为每个方法创建一个带有委托的存根类。 In WPF/Silverlight ICommand is implemented that way, you have a DelegateCommand class wich receives a Func to implement bool CanExecute(object parameter) and an Action to implement Execute(object parameter). 在WPF / Silverlight中,以这种方式实现ICommand,您将拥有一个DelegateCommand类,该类将接收一个用于实现bool CanExecute(对象参数)的Func和一个用于实现Execute(对象参数)的Action。 The most correct way to do it in code generation is with T4 templates, create a template and a parameter in it (for example a string indicating the class name of the class you want to create a Delegateclass for, and use reflection to produce the code). 在代码生成中最正确的方法是使用T4模板,在其中创建模板和参数(例如,一个字符串,该字符串指示要为其创建Delegateclass的类的类名,并使用反射来生成代码)。

Hope i helped 希望我有所帮助

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

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