简体   繁体   English

使用抽象接口成员的具体实现实现接口

[英]Implement interface using concrete implementations of abstract interface members

Is there a specific reason why the following is not possible? 是否存在以下不可能的具体原因?

class ClassOfInts : IHaveInts
{
    public MyInt IntHolder { get; }
    // This solves my use case but i'm unsure why this is necessary
    // IInt IHaveInts.IntHolder { get => IntHolder; }
}

interface IHaveInts
{
    IInt IntHolder { get; }
}


class MyInt : IInt
{
    public int TheInt { get; }
}

interface IInt
{
    int TheInt { get; }
}

I would think that the above code successfully implements IHaveInts since MyInt implements IInt. 我认为上面的代码成功实现了IHaveInts,因为MyInt实现了IInt。

Is there a specific reason why the following is not possible? 是否存在以下不可能的具体原因?

Well, the short answer is: "because the C# specification doesn't allow it". 嗯,简短的回答是:“因为C#规范不允许它”。 Longer answers typically involve some amount of speculation as to what was in the thought process of the C# language designers. 更长的答案通常涉及一些关于C#语言设计者思维过程中的内容的猜测。 That makes such questions primarily opinion based. 这使得这些问题主要以意见为基础。

However, they did make a deliberate choice that interface members have to be implemented precisely as declared, and that choice is why you can't do that. 但是,他们确实做了一个深思熟虑的选择,接口成员必须按照声明的方式精确实现,而这种选择就是为什么你不能这样做。 A likely reason behind that choice is that they would have to special-case read-only properties, because allowing the property to be implemented that way for a writeable property would be unsafe. 这种选择背后的一个可能原因是它们必须具有特殊情况的只读属性,因为允许以可写属性的方式实现该属性将是不安全的。 Were they to allow that, you'd be able to assign any IInt value to the property which expects only MyInt values. 是他们,让这一点,你会能够任意分配IInt值,其预计只有财产MyInt值。

That said, depending on what you're actually trying to do, you might be able to use generic type variance to support your scenario. 也就是说,根据您实际尝试的操作,您可以使用泛型类型差异来支持您的方案。 This will compile fine: 这将编译好:

public class ClassOfInts : IHaveInts<MyInt>
{
    public MyInt IntHolder { get; }
}

public interface IHaveInts<out T> where T : IInt
{
    T IntHolder { get; }
}

Declared that way, the following works fine: 宣布这种方式,以下工作正常:

static void M()
{
    IHaveInts<IInt> haveInts = new ClassOfInts();
}

This is semantically equivalent to what you were originally trying to do. 这在语义上等同于您最初尝试的操作。 That is, when using the interface type, you have a property of type IInt , but you want to implement that property with a member that returns a value of type MyInt . 也就是说,使用该接口类型的时候,你有类型的属性IInt ,但要实现与返回类型的值的部件,其性能MyInt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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