作者:晨心晨艺日记 | 来源:互联网 | 2022-12-07 17:28
我有一个接口,由更多存储了附加信息的类实现.我需要能够转换实现而不明确地说它是这一个实现.
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
.我可以更改接口及其实现,但不能更改方法.
1> BradleyDotNE..:
我不知道我会得到哪个对象所以我必须做一些东西,可以将任何东西转换成它的原始类型.
那时你打算用它做什么?由于您不知道类型,因此您不知道可以调用哪些方法等.这就是您的原始解决方案返回的原因object
.
你可以使用dynamic
但是如果你试图使用一个不存在的方法就可以抛出.你得到的最接近的是简单的is
检查(简洁的C#7模式匹配):
if (animal is Dog dog)
//Do stuff with dog
else if (animal is Rhino rhino)
// Do stuff with rhino
大胖子免责声明:向下倾斜是一个巨大的红旗.当你甚至不知道期望什么类型时,向下倾斜甚至更糟.您的设计几乎肯定需要重新考虑.