C# 不允许派生类';实现接口的具体属性';s接口属性?

C# 不允许派生类';实现接口的具体属性';s接口属性?,c#,.net,C#,.net,这是一个非常简单的例子 public interface IMyInterfaceProperty { } public class MyProperty : IMyInterfaceProperty { } public interface IMyInterface { IMyInterfaceProperty SomeProperty { get; set; } } public class MyClass : IMyInterface { public MyPrope

这是一个非常简单的例子

public interface IMyInterfaceProperty
{
}

public class MyProperty : IMyInterfaceProperty
{
}

public interface IMyInterface
{
    IMyInterfaceProperty SomeProperty { get; set; }
}

public class MyClass : IMyInterface
{
    public MyProperty SomeProperty { get; set; }
}
在此示例中,
MyProperty
是从
IMyInterfaceProperty
派生的,但不允许。不允许编译此文件背后的思想过程是什么


Program.MyClass
未实现接口成员
Program.IMyInterface.SomeProperty
Program.MyClass.SomeProperty
无法实现
Program.IMyInterface.SomeProperty
,因为它没有与
Program.IMyInterfaceProperty
匹配的返回类型,甚至不允许以下情况:

public interface IMyInterface
{
    IMyInterfaceProperty SomeProperty { get; set; }
    MyProperty SomeProperty { get; set; }
}
我认为原因是类型中不允许具有相同签名的成员。此处不考虑返回值:

方法的签名不包括返回 类型,也不包括可能指定的参数修饰符 对于最右边的参数


(从。虽然它是针对VS2003的,但我认为从那时起就没有改变:)

,因为它不是类型安全的

如果
MyClass
实现了
IMyInterface
,则
MyClass
的实例需要能够在
IMyInterface
变量中工作(Liskov替换原则)。让我们看看这意味着什么:

除了您定义的类型之外,我们还假设:

public class EvilProperty : IMyInterfaceProperty {}

public static class X
{
    public static void EvilMethod(IMyInterface a, IMyInterfaceProperty b)
    {
        a.SomeProperty = b;
    }
}
现在,这是电话(振作起来!):


看看会发生什么?该方法将
EvilProperty
的实例分配给
MyClass
实例的
SomeProperty
,但该属性需要一个
MyProperty
,并且
EvilProperty
不会从
MyProperty

继承,要实现的方法应该具有相同的签名和返回值。如果您需要不同的返回值,您可以使用泛型:
T SomeProperty{get;set;}
这更多地参考了ASP.Net MVC,因为默认的模型绑定器无法在我的类上创建接口来填充它的值(因此,在我的构造函数中,我必须手动使用一个具体的类填充接口,而不是允许MVC为我实例化该类。)
X.EvilMethod(new MyClass(), new EvilProperty());