首页 > 解决方案 > 将接口转换为其实现

问题描述

我有一个由更多类实现的接口,这些类存储了额外的信息。而且我需要能够在不明确说明这是一个实现的情况下转换实现。

public interface IAnimal
{
    string Name { get; set; }
    Type GetType();
}

public class Dog : IAnimal
{
    public string Name { get; set; }
    Type GetType() {return typeof(Dog);}
    public int TimesBarked { get; set; }
}

public class Rhino : IAnimal
{
    public string Name { get; set; }
    Type GetType() {return typeof(Rhino);}
    public bool HasHorn { get; set; }
}

通过大部分代码,我毫无问题地使用了接口,但在某些时候,我需要将实现转换为其原始类型。

IAnimal animal = new Dog
{
    Name = "Ben",
    TimesBarked = 30
}
// Doing stuff with Ben

// In some other function
AnotherObject.SomeMethodThatNeedsToKnowType(animal) //Needs to be Converted before putting here

我不知道我会得到哪个对象,所以我必须制作一些可以将任何东西转换为其原始类型的东西。不幸的是没有Convert.ChangeType(animal, animal.GetType())回报。我可以更改接口及其实现,但不能更改方法。object{Dog}Dog

标签: c#

解决方案


我不知道我会得到哪个对象,所以我必须做一些可以将任何东西转换为原始类型的东西。

那时你打算用它什么?由于您不知道类型,因此您不知道可以调用哪些方法等。这就是您的原始解决方案返回object.

您可以使用dynamic,但如果您尝试使用一种不存在的方法,它只会抛出。您将得到的最接近的是简单is检查(为简洁起见,C# 7 模式匹配):

if (animal is Dog dog) 
   //Do stuff with dog
else if (animal is Rhino rhino)
   // Do stuff with rhino

大胖免责声明:垂头丧气是一个巨大的危险信号。当您甚至不知道该期待什么类型时,垂头丧气会更糟。您的设计几乎肯定需要重新考虑。


推荐阅读