开发者

Defining a property of type 'class1 : interface1' into another interface

I have some classes which implement an interface as follows:

class C1 : IpropTemplate { ... }

class C2 : IpropTemplate { ... }

:

Also there is some other class which implements another interface:

class C3 : IclassTemplate { ... }

Now, I need to specify the signature of a property into the IclassTemplate that forces the C3 to have a property which is implemented from IpropTemplate. (such as C1 or C2, etc.)

I tried this:

interface IclassTemplate
{
    ...
    IpropTemplate prop1 { get; set; }
}

class C3 : IclassTemplate
{
    ...
    public C1 prop1
    {
        get;
        set;
    }
}

In this case, compiler produces an error indicating that C3 does not implement interface member IclassTemplate.prop1 and that the C3.prop1 cannot implement IpropTemplate.prop1 because it does not have the matching return 开发者_高级运维type of IpropTemplate.

What should I do? Thanks


You can't make your C3 implementation only deal in C1 - after all, you've guarantee that this will be valid:

IClassTemplate c3 = new C3();
c3.Template = new C2();

If you only need to be able to read the property, it's slightly easier:

interface IClassTemplate
{
    IPropTemplate Template { get; }
}

public class C3 : IClassTemplate
{
    private readonly C1 c1 = new C1();

    IPropTemplate Template { get { return c1; } }
}

That lets the code in C3 know that it's really a C1, but still implement the interface.

Another option is to make your interface generic:

interface IClassTemplate<T> where T : IPropTemplate
{
    T Template { get; set; }
}

public class C3 : IClassTemplate<C1>
{
    public C1 Template { get; set; }
}

Hopefully one of these will meet your need - if not, please give more details about what you're really trying to achieve - the bigger picture.


The return type is part of the signature of the property - it has to be of type IpropTemplate:

public IpropTemplate prop1
{
    get;
    set;
}

Then you can assign it to a C1 ans well as C2 objects.

...
prop1 = new C1();


Instead of C1 , write IPropTemplate in property signature. After infernaly you can operate on C1 type, but the signature has to expose an interface as IclassTemplate defined it in that way.


Just do

class C3 : IclassTemplate 
{
    ...
    public C1 prop1
    {
        get;
        set;
    }
   public IpropTemplate prop1 {get;set;}
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜