c# - 将接口转换为其实现
问题描述
我有一个由更多类实现的接口,这些类存储了额外的信息。而且我需要能够在不明确说明这是一个实现的情况下转换实现。
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
解决方案
我不知道我会得到哪个对象,所以我必须做一些可以将任何东西转换为原始类型的东西。
那时你打算用它做什么?由于您不知道类型,因此您不知道可以调用哪些方法等。这就是您的原始解决方案返回object
.
您可以使用dynamic
,但如果您尝试使用一种不存在的方法,它只会抛出。您将得到的最接近的是简单is
检查(为简洁起见,C# 7 模式匹配):
if (animal is Dog dog)
//Do stuff with dog
else if (animal is Rhino rhino)
// Do stuff with rhino
大胖免责声明:垂头丧气是一个巨大的危险信号。当您甚至不知道该期待什么类型时,垂头丧气会更糟。您的设计几乎肯定需要重新考虑。
推荐阅读
- c++ - 如何在win32的窗口类中设置动态菜单?
- javascript - windows onbeforeunload 不起作用 Javascript
- android - 如何在 React Native 中请求位置权限?
- css - 材料设计中的标签截断
- azure - Microsoft.Azure.Mobile 客户端 - 使用自定义 IMobileServiceSyncHandler 处理服务器错误 - Xamarin Forms
- oracle - oracle表上的ROWID
- javascript - jQuery dataTable 错误无法读取未定义的属性“mData”
- php - 如何循环 PHP 的 PDO 绑定参数
- mysql - 为什么MYSQL将列标识为表?
- linux - 使用命令行按 key=value 字段对日志文件进行排序