If you have a method which is overloaded with a derived type, the method called at run-time depends on the type of your variable, even if the underlying object is actually of the derived type:
class Program
{
static void Main(string[] args)
{
BaseClass theBaseObject = new BaseClass
{
Foo = "FOO"
};
DerivedClass theDerivedObject = new DerivedClass
{
Foo = "FOO",
Bar = "BAR"
};
Processor processor = new Processor();
Console.WriteLine(processor.Compose(theBaseObject));
Console.WriteLine(processor.Compose(theDerivedObject));
Console.WriteLine(processor.Compose((BaseClass) theDerivedObject));
}
}
public class Processor
{
public string Compose(BaseClass item)
{
return item.Foo;
}
public string Compose(DerivedClass item)
{
return Compose((BaseClass)item) + item.Bar;
}
}
public class BaseClass
{
public string Foo { get; set; }
}
public class DerivedClass : BaseClass
{
public string Bar { get; set; }
}
Actual Output:
FOO
FOOBAR
FOO
I would like to find a way to alter this behaviour such that the most specific method invoked for a given parameter.
Desired output:
FOO
FOOBAR
FOOBAR // because theDerivedObject is an instance of DerivedClass
This would allow specific processing for a bunch of items, all derived from a base.
Is this possible in c#?
Edit:
A clarification - in practice there would be no explicit cast, as the items would likely be in a list of collection of mixed types:
Example using a list without an explicit cast:
foreach (BaseClass item in new []{ theBaseObject, theDerivedObject })
{
Console.WriteLine(processor.Compose(item));
}
Actual output:
FOO
FOO
Desired output:
FOO
FOOBAR
Obviously the cast is still happening - but it's not easy to remove it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…