开发者

(un)Inheritance in C#

开发者 https://www.devze.com 2023-03-30 11:01 出处:网络
this is strange but I really need it. I need to inherit a class without inherit their base class but I don\'t know how.

this is strange but I really need it. I need to inherit a class without inherit their base class but I don't know how.

I have a base abstract entity class from a framework like this:

public abstract class AbstractEntity
{
    public bool Validate(){};
    public List<ValidationErrors> erros;

    // and so many more properties and methods
}

My custom class inherit this abstract base class:

public class Contact : AbstractEntity
{
    public int id
    public string name;
    public string phone;
}

I'm using this class Contact on a webservice and I need only the custom properties, how can I re-use the class Contact without the inheritance AbstractEntity?

I don't want to duplicate this class. Sorry if this sounds stupid.

EDI开发者_StackOverflow社区T

This is a project already created with a code generator, I can't change the classes structures. For this reason I wanted to instantiate that class without the abstract class.

As I can not change it now and need it urgently, I will duplicate this class without the abstraction and use it.


Sounds like you need an interface.

Extract an interface (IAbstractEntity) from AbstractEntity. Or maybe IContact from Contact- the question isn't very clear about which class has the methods and properties that you want to share. It would looks something like this:

public interface IContact
{
    int Id { get; }
    string Name { get; }
    string Phone { get; }
}

Implement IContact on Contact. Then modify any methods that only use the particular methods/properties in IContact to use an IContact instead of Contact.

And I agree with @Jamie-Penney, it sounds like you should read http://en.wikipedia.org/wiki/Data_transfer_object

Finally, if this is a DTO, you are probably going to find yourself in need of something like AutoMapper


As far as I know you cannot break the inheritance chain. If you want a Contact that doesn't inherit AbstractEntity, you must create a new Contact class that doesn't list AbstractEntity as a parent.

Sorry, that's just how C# is designed.


Try containment.

public class NotAnEntity 
{
    public Contact { get; set; }

    public static implicit operator Contact(NotAnEntity other)
    {
        return other.Contact;
    }
}


While I think that using a simple DTO would probably be the easiest solution, another option would be to implement the IXMLSerializable interface on your Contact class and have it only serialize the properties you care about. Of course, this would affect the XML serialization of the object in other situations as well, not just with the web services.

0

精彩评论

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