代码之家  ›  专栏  ›  技术社区  ›  Bug

类实现接口并将其作为属性公开

c#
  •  1
  • Bug  · 技术社区  · 2 年前

    您认为以下代码是否创建了一些循环引用?

    public interface IMyInterface
    {
           
    }
    
    public class MyClass : IMyInterface
    {
        public IMyInterface  MyInterface { get; set; }
    }
    
    public class AnotherClass : IMyInterface
    {
    
    }
    
    3 回复  |  直到 2 年前
        1
  •  2
  •   Mosia Thabo    2 年前

    您使用界面的方式是正确的。不会出现循环引用。

    here

    此外,这里还有另一个来自 Tutorials point

        2
  •  2
  •   AMunim    2 年前

    不,它不会创建循环引用,您的类可以继承一个接口“foo”,并具有另一个具有不同实现的“foo”。

    
    public interface Foo{ }
    
    public class Bar: Foo {}
    
    public class Baz : Foo
    {
       public Foo foo;
       public Baz()
       {
           foo = new Bar();
       }
    }
    

    即使是同一类型,如果它们是不同的实例,也可以工作。

    public Bar: Foo
    {
       public Foo bar;
       public Bar()
       {
    
       }
    
       //this works because they are different instances of the same object.
       public void AddBar(Bar bar)
       {
          this.bar = bar;
       }
    }
    

    即使您有相同的实例,它也不应该中断,因为这就是单例模式的工作方式,您可以创建一个静态属性来保存同一个类的静态实例。

        3
  •  0
  •   Alpha75    2 年前

    MyClass ,充当自身的包装器,这是一种非常常用的模式。