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.
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). 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?
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). 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). 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).
Hope i helped
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.