2017-01-06 72 views
0

我正在使用旧的(.NET 1)API,我无法更改。该API没有接口。我有一个基本类(Pet)与具体类(Cat,Parrot)基本上有'相同'的方法(GetLegs())。我希望我的帮助器类'摘除',并使用实例的类型调用方法。我想避免反思。不同类型的具有相同名称的调用方法

我的尝试有我的类型切换。这是一个合理的方法吗?我应该担心(在'理论'层面上)Type过于笼统吗?

namespace TheApi 
{ 
    public class Pet 
    { 
    } 

    public class Cat : Pet 
    { 
     public string[] GetLegs() => 
      new[] { "Front left", "Front right", "Back left", "Back right" }; 
    } 

    public class Parrot : Pet 
    { 
     public string[] GetLegs() => 
      new[] { "Left", "Right" }; 
    } 
} 

namespace MyApp 
{ 
    using System; 
    using System.Collections.Generic; 
    using NUnit.Framework; 
    using TheApi; 
    public static class Helper 
    { 
     public static string[] GetLegsFor(Pet pet) 
     { 
      return MapTypeToGetter[pet.GetType()](pet); 
     } 

     private static Dictionary<Type, Func<Pet, string[]>> MapTypeToGetter => 
      new Dictionary<Type, Func<Pet, string[]>> 
      { 
       [typeof(Cat)] = p => ((Cat)p).GetLegs(), 
       [typeof(Parrot)] = p => ((Parrot)p).GetLegs() 
      }; 
    } 

    public class Tests 
    { 
     [Test] 
     public void Test() 
     { 
      Pet bird = new Parrot(); 
      var legs = Helper.GetLegsFor(bird); 

      var expectedLegs = new[] { "Left", "Right" }; 
      Assert.That(legs, Is.EqualTo(expectedLegs)); 
     } 
    } 
} 
+4

你应该有一个接口 - 'IHaveLegs'。 –

+4

为什么不简单地在'Pet'上使用扩展方法? –

+1

@ DanielA.White OP说:我正在处理一个旧的(.NET 1)API,我无法改变。该API没有接口。 – CodingYoshi

回答

2

我想帮助我的班“abtract走”,只是调用使用实例的类型的方法。我想避免反思。

我根本就不写辅助类。我会写一个扩展方法:

namespace PetesExtensions 
{ 
    public static class PetExtensions 
    { 
    public static string[] GetLegs(this Pet pet) 
    { 
     if (pet == null) throw new ArgumentNullException("pet"); 
     if (pet is Cat) return ((Cat)pet).GetLegs(); 
     if (pet is Parrot) return ((Parrot)pet).GetLegs(); 
     throw new Exception(
     $"I don't know how to get the legs of a {pet.GetType().Name}. Contact Pete Moloy."); 
    } 
    } 
} 

然后你就可以说

using PetesExtensions; 
... 
Pet p = whatever; 
string[] legs = p.GetLegs(); 
+0

嗨,埃里克,我试图啃OOP的概念。创建扩展方法与接口的优点是什么?假设我想创建一个'Worm'类,它可以是'pet',但没有腿。我不会更好地使用界面,所以我可以选择哪个宠物会不会腿?谢谢。 – Zuzlx

+2

@Zuzlx:当然会更好。问题的前提是使用接口是不可能的。重新阅读问题的前两句。 –

+0

扩展方法是语法糖,我可以添加到我的。但是你的方法与我的真实不同,即我们都开启了类型,不是? – petemoloy

相关问题