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

返回接口的方法

c#
  •  3
  • Hosea146  · 技术社区  · 15 年前

    我对返回接口的方法的概念有点困惑。是否有文章或参考文献对此进行了详细讨论?我对您可能希望何时/为什么这样做感到困惑,以及如何向与之关联的对象(我认为这是正确的)强制转换接口。

    4 回复  |  直到 15 年前
        1
  •  14
  •   Mark Byers    15 年前

    IFoo SimpleFoo AdvancedFoo

    List<T> IEnumerable<T>

    IFoo foo = getFoo();
    SimpleFoo simpleFoo = (SimpleFoo)foo;
    

    as

    IFoo foo = getFoo();
    SimpleFoo simpleFoo = foo as SimpleFoo;
    if (simpleFoo == null)
    {
         // Too bad...
    }
    else
    {
        // Now we can use simpleFoo.
    }
    
        2
  •  1
  •   myermian    15 年前

    public interface IFooBar
    {
        String GetData();
    }
    
    public class Foo : IFooBar
    {
        public String GetData() { return "Foo"; }
    }
    
    public class Bar : IFooBar
    {
        public String GetData() { return "Bar"; }
    }
    
    public class DataManager
    {
        public static IFooBar GetFooBar()
        {
            IFooBar foobar = ...
            return foobar;
         }
    }
    
    public class MainAppClass
    {
         public void SomeMethod()
         {
             //You don't care what type of class you get here
             //you only care that the object you get back let's you
             //call GetData.
             IFooBar foobar = DataManager.GetFooBar();
             String data = foobar.GetData();
             //etc
         }
    }
    
        3
  •  0
  •   siride    15 年前

        4
  •  0
  •   Gordon Gustafson    15 年前

    using System.Collections.Generic;
    
    ICollection<int> getCollection() {
        return new LinkedList<int>();
    }
    

    C# interfaces tutorial