返回接口的自动属性

时间:2009-11-04 23:36:57

标签: c# interface automatic-properties

这是我今天在编码中看到的好奇心。

以下是示例代码:

public class SomeClass
{
   public IUtils UtilitiesProperty { get; set; }
}

public interface IUtils
{
   void DoSomething();
}

public class Utils : IUtils
{
   void DoSomething();
}

编译好。

那么什么是UtilitiesProperty?它是一个Util?如果不止一个班级实施了IUTil怎么办?它会在编译失败吗?

2 个答案:

答案 0 :(得分:13)

在你给它一个之前它没有任何价值(或者更确切地说,它具有值null)。如果您为其分配Utils引用,则为:它是Utils,通过IUtils接口公开。您只能提供null或实施IUtils的内容。

答案 1 :(得分:5)

它是一个可以容纳实现IUtils接口的对象的属性。更多的类可以实现这个接口,使用接口可以实现抽象级别(只要类遵守接口契约,消费者就不会在意)。

我建议您阅读有关接口,抽象类等的使用。

例如MSDN docs