我有一个具有 x 个属性的基类,然后我有一个具有更多属性的派生类。如何处理方法中的公共(public)字段,然后将对象发送到另一个可以处理其附加属性的方法?
例子:
public Interface IAnimal {
int NoOfFeet;
}
class Animal: IAnimal {
int NoOfFeet {get;set;}
}
class Elephant: Animal {
bool hasTrunk {get;set;}
}
class Dog:Animal {
string canBark {get;set;}
}
Method1(IAnimal a) {
//process NoOfFeet ...
//process fields for derived type
DoSomething(IAnimal a)
}
DoSomething(Elephant e) {
//process trunk
}
DoSomething(Dog d) {
//process canbark
}
最佳答案
听起来您基本上希望在执行时解决重载问题。 (我假设你不能引入一个虚拟方法来做正确的事情,并在每个类中实现它。如果实现知道你在用它们做什么是合理的,那将是最干净的方法,但那是并非总是如此。)最简单的实现方式是使用 dynamic
,如 C# 4 中所介绍的:
public void Method(IAnimal animal)
{
// We don't want to call Handle with a null reference,
// or we'd get an exception to due overload ambiguity
if (animal == null)
{
throw new ArgumentNullException("animal");
}
// Do things with just the IAnimal properties
Handle((dynamic) animal);
}
private void Handle(Dog dog)
{
...
}
private void Handle(Elephant elephant)
{
...
}
private void Handle(object fallback)
{
// This method will be called if none of the other overloads
// is applicable, e.g. if a "new" implementation is provided
}
关于c# - 将具有相同接口(interface)或基类的类传递给重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897144/