简体   繁体   中英

C# Implement derived Types of an Interface Definition?

I have an inheritance tree, which looks like this:

Foo and Bar both have an Id , as defined through an specific Id class. The id classes itself are derived from a common base class.

I would now like to write an interface which can encompass both Foo and Bar , but the compiler does not allow that, I would have to use BaseId as the type in Foo and Bar , but I would like to avoid that.

public class BaseId
{
    public string Id {get; set;}
}

public class FooId: BaseId
{}

public class BarId: BaseId
{}

public interface MyInterface
{
    public BaseId Id {get; set; }
}

public class Foo: MyInterface
{
    public FooId Id {get; set;}
}

public class Bar: MyInterface
{
    public BarId Id {get; set;}
}

Generics can help here. First you define interface like this:

public interface IMyInterface<out T> where T : BaseId {
    T Id { get; }
}

And then you can implement it like this:

public class Foo : IMyInterface<FooId> {
    public FooId Id { get; set; }
}

public class Bar : IMyInterface<BarId> {
    public BarId Id { get; set; }
}

Achieving your goal to use BarId and FooId in specific classes.

Both classes are also castable to IMyInterface<BaseId> in case you are in situation where you don't know the exact id type:

Foo foo = new Foo();
// works fine
var asId = (IMyInterface<BaseId>)foo;

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