lundi 29 janvier 2018

Passing C# parameters which can "fit" an interface, but do not actually implement it

Note: I know this is an awful idea in practice; I'm just curious about what the CLR allow you to do, with the goal of creating some sort of 'modify a class after creating it' preprocessor.

Suppose I have the following class, which was defined in another assembly so I can't change it.

class Person {
    public string Greet() => "Hello!";
}

I now define an interface, and a method, like the following:

interface IGreetable {
    string Greet();
} 

// ...

void PrintGreeting(IGreetable g) => Console.WriteLine(g.Greet());

The class Person does not explicity implement IGreetable, but it could do without any modification to its methods.

With that, is there any way whatsoever, using Reflection, the DLR or anything else, in which an instance of Person could be passed successfully to PrintGreeting without modifying any of the code above?





Aucun commentaire:

Enregistrer un commentaire