Reputation: 1535
Trying to figure out the .NET equivalent using generics (been away doing Java for several years). Here's some pseudo code for what I want:
abstract base class MyBase
abstract property string Name;
abstract property ObservableCollection<T> SubItems;
Then I have 2 classes that inherit from myBase each would implement the 2 properties and the types of objects inside the collection would e different.
class Real1 : MyBase
property string Name
property ObservableCollection<SomeClass> SubItems;
class Real2 : MyBase
property string Name
property ObservableCollection<SomeDifferentClass> SubItems;
The point is to allow these items to be bound to a TreeView that requires all the child elements to have the same property name (for xaml binding). If I have to create new collections with a common type I'll have to iterate through each and they are large. I do not control the original collection data, so I can't modify those classes.
Upvotes: 0
Views: 575
Reputation: 646
I do agree with Stanley. Just because you can create an abstract class doesn't mean you should. Here is the scenario when you do need an abstract class:
Suppose you are creating a method in static class to handle animal sound and do something, for example
public static class AnimalHelper {
public static string NotifySound(this Animal animal) {
return animal. GetType().Name + " " + animal.Sound.ToString() + "s";
}
}
Now here you don't know your animal and it's SoundType. So you create an abstract class:
public abstract class Animal {
public abstract SoundType Sound{get;}
}
public enum SoundType{
Bark,
Roar,
Meow
}
public class Dog:Animal {
public override SoundType Sound { get { return SoundType.Bark; } }
}
public class Lion:Animal {
public override SoundType Sound { get { return SoundType.Roar; } }
}
So here you have created universal method for handling sound using power of OOP. I hope this gives you right perspective to use abstraction.
Upvotes: 0
Reputation: 152566
It sounds like you want a generic base class:
abstract class MyBase<T>
{
public abstract string Name {get; set;}
public abstract ObservableCollection<T> SubItems {get; set;}
}
class Real1 : MyBase<SomeClass>
{
public override string Name {get; set;}
public override ObservableCollection<SomeClass> SubItems {get; set;}
}
class Real2 : MyBase<SomeDifferentClass>
{
public override string Name {get; set;}
public override ObservableCollection<SomeDifferentClass> SubItems {get; set;}
}
but unless the implementation of the properties is different, I don't see why you need an abstract base class, and it's not clear why you need subclasses at all. You can create a MyBase<SomeClass>
without having to have a defined sub-type.
Upvotes: 3