开发者

In a child class, how to get different types for a specific property?

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 appr开发者_开发问答opriate 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.


One obvious approach is to make VisualBase generic:

class VisualBase<T> where T : BusinessBase
{
    T BusinessObject {get; set;}
}

class VisualChild1 : VisualBase<BusinessChild1>
{
    ...
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜