Reputation: 1491
I have the following classes:
class BusinessBase { }
class BusnessChild: BusinessBase { }
class VisualBase
{
BusinessBase BusinessObject {get; set;}
}
class VisualChild: VisualBase
{
// I'm instantiate an instance of BusinessChild and
// assign it to BusinessObject property
}
In every instance visual child there's an object of BusinessChild
instance from that appropriate type.
I mean they are BusinessChild1
and BusinessChild2
for VisualChild1
and VisualChild2
and all of them are inherited from VisualBase
and BusinessBase
.
The question is:
Is there a way to get an instance of BusinessChild
from VisualChild
without creating a new property in the child class? because I want to deal with all children instances from a parent reference.
What I thought so far is creating a generic method called GetBusinessObject<T>
and pass the appropriate business type to it, but I wonder if it can be done automatically in someway (without passing the type).
Please ask me for further information if it's not clear.
Upvotes: 1
Views: 113
Reputation: 29468
You could decorate the derived class with a custom attribute:
[BusinessObjectTypeAttribute(typeof(VisualChild))]
class VisualChild: VisualBase
{
// I'm instantiate an instance of BusinessChild and
// assign it to BusinessObject property
}
Then you read out this attribute with GetCustomAttributes()
and create the instance with Activator.CreateInstance()
and pass the type to it.
Upvotes: 0
Reputation: 1500385
One obvious approach is to make VisualBase
generic:
class VisualBase<T> where T : BusinessBase
{
T BusinessObject {get; set;}
}
class VisualChild1 : VisualBase<BusinessChild1>
{
...
}
Upvotes: 3