c# - 传递可以 "fit"接口(interface)的 C# 参数,但实际上并不实现它

标签 c# class reflection system.reflection

注意:我知道这在实践中是一个糟糕的想法;我只是好奇 CLR 允许您做什么,目标是创建某种“在创建类后修改它”的预处理器。

假设我有以下类,它是在另一个程序集中定义的,所以我无法更改它。

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

我现在定义一个接口(interface)和一个方法,如下所示:

interface IGreetable {
    string Greet();
} 

// ...

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

Person 类没有显式实现 IGreetable,但它可以在不对其方法进行任何修改的情况下实现。

有了这个,有什么方法可以使用反射、DLR 或其他任何方法,在其中 Person 的实例可以成功传递给 PrintGreeting 而无需修改任何上面的代码?

最佳答案

尝试使用库Impromptu-Interface

[The Impromptu-Interface] framework to allow you to wrap any object (static or dynamic) with a static interface even though it didn't inherit from it. It does this by emitting cached dynamic binding code inside a proxy.

这允许你做这样的事情:

var person = new Person();
var greeter = person.ActLike<IGreetable>();

关于c# - 传递可以 "fit"接口(interface)的 C# 参数,但实际上并不实现它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48508011/

相关文章:

c# - 在 C# 中等效的 Javascript atob(string)

c# - Linq 查询适用于 null 但不适用于 int?在 where 子句中

Python 类属性和子类化

C#:泛型类中的嵌套类是否应该被视为泛型?

java - 任何高级字节码编辑器?

reflection - 映射受歧视联合中的所有值

c# - 如何读取 XNA 中特定像素的颜色?

c# - 在 Visual Studio 中关闭蓝线

c# - 从 JSON 数据构建对象?

python - 类/函数全局变量没有在 Python 中返回?