我正在使用旧的(.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));
}
}
}
你应该有一个接口 - 'IHaveLegs'。 –
为什么不简单地在'Pet'上使用扩展方法? –
@ DanielA.White OP说:我正在处理一个旧的(.NET 1)API,我无法改变。该API没有接口。 – CodingYoshi