简体   繁体   中英

How to use an interface in an interface

I want to create an interface which can handle multiple other object of one interface.

I tried using the interface in the interface and using an object in the new class.

public interface IObject
{
    double Value { get; set; }
}

public class FirstObject: IObject
{
    double Value { get; set; }
}

public class SecondObject: IObject
{
    string Titel { get; set; }
    double Value { get; set; }
}

public interface ICollection
{
    IObject[] Values { get; set; }
}

public class Collection: ICollection
{
    SecondObject[] Values { get; set; }
}

Now I get the error, that my Collection doesn't implement the IObject[] Values member.

I thought when I use an object ( SecondObject ) wich is implementing from the interface IObject the Collection should handle this.

What am I doing wrong and how can I solve this?

You might be off better here using generics:

public interface ICollection<T> where T : IObject
{
    T[] Values { get; set; }
}

public class Collection : ICollection<SecondObject>
{
    public SecondObject[] Values { get; set; }
}

The reason that it doesn't work now, is that the signature should match exactly. That means the Values should be an array of IObject , which it isn't. Using generics you can solve this, while keeping the type constraint.

A second, but inadvisable solution would be using an explicit interface implementation:

public SecondObject[] Values { get; set; }

IObject[] ICollection.Values
{
    get
    {
        return this.Values;
    }
    set
    {
        this.Values = value?.Cast<SecondObject>().ToArray();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM