c# - 接口(interface)的动态实现

标签 c#

假设我有一个具有一些属性的接口(interface):

public interface IDummy
{
    string First  {get;set;}
    string Second {get;set;}
    string Third  {get;set;}
    string Fourth {get;set;}
}

现在,我有一个实现该接口(interface)的类:

public class DummyClass: IDummy
{
    // ...
}

是否可以不显式实现接口(interface)属性而是使用 DynamicObject?例如:

public class DummyClass: DynamicObject, IDummy
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        // Get the value from a Config file or SQLite db or something
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        // Get the value to a Config file or SQLite db or something
    }
}

我只是好奇这是否可能? 谢谢。

最佳答案

不,这是不可能的。

如果你正在实现一个接口(interface),你需要实现它的所有成员。毕竟,C# 仍然是一种静态类型语言。

当你说一个类型实现了一个接口(interface)时,你是在说它符合它的契约。不实现所有成员意味着您遵守契约(Contract)。

编译器会看到您的代码,并且不会假定您已经正确地(以动态方式)实现了契约——它将无法编译。

关于c# - 接口(interface)的动态实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464603/

相关文章:

c# - 在 DrawText win32 函数中设置格式

c# - 如何在静态类中使用 IHttpContextAccessor 设置 cookie

c# - 使用 json.net 序列化值类型

c# - 在图片框、窗体上查找碰撞区域

c# - 字典作为参数传递时会丢失值

c# - 我怎样才能从队列中创建一个 IObservable,这样序列就不会在队列为空时结束?

c# - 支持异步操作的自定义线程池

c# - 在 ASP.NET Core 2.x 中实现 EasyNetQ 发布/订阅模式的正确方法是什么?

c# - 错误 "Could not create SSL/TLS secure channel."尽管手动设置 TLS

c# - 如何通过反射C#获取类中属性的数据类型