c# - 如何对已定义为接口(interface)的属性进行强类型化?

标签 c# interface

我正在尝试对已定义为接口(interface)中的接口(interface)的对象属性进行强类型化。这是我的样本

// interfaces
public interface IMyInterfaceA
{
    string A { get; set; }
    IMyInterfaceB B { get; set; }
}

public interface IMyInterfaceB
{
    string B { get; set; }
}

// POCOs
public class pocoOneB : IMyInterfaceB
{
    public B { get; set; }
    public C { get; set; }  // extending the poco with a non-interfaced property
}

public class pocoOneA : IMyInterfaceA
{
    string A { get; set; }
    pocoOneB B { get; set; }  // fails, can I strongly type an interface??
}

public class pocoTwoB : IMyInterfaceB
{
    public B { get; set; }
    public D { get; set; }  // extending the poco with a non-interfaced property
}

public class pocoTwoA : IMyInterfaceA
{
    string A { get; set; }
    pocoTwoB B { get; set; } // fails, can I strongly type an interface??
}

问题是我做不到

pocoOneB B { get; set; } // fails, can I strongly type an interface??

pocoTwoB B { get; set; } // fails, can I strongly type an interface??

即使它们是接口(interface)的实现,编译器也会说我没有在任一 poco 上正确实现 IMyInterfaceA。我理解该错误,但是我想知道是否有一种方法可以对具有接口(interface)的属性进行强类型化?

解决这个问题的一种方法是不让接口(interface) IMyInterfaceA 定义接口(interface) IMyInterfaceB 的属性,并且在 poco 上扩展,但是我试图强制使用接口(interface)来实现该属性。

我需要强类型化 poco 属性的主要原因是因为我使用 JSON 通过网络进行反 sanitizer 。

感谢您的指导。

最佳答案

public interface IMyInterfaceA<TPoco>
   where TPoco : IMyInterfaceB
{     
   TPoco B { get; set; } 
} 

public class pocoOneA<TPoco> : IMyInterfaceA<TPoco>
  where TPoco : IMyInterfaceB
{     
   public TPoco B { get; set; }  // fails, can I strongly type an interface?? 
} 

或者简单地

public interface IMyInterfaceA
{     
   IMyInterfaceB B { get; set; } 
} 

public class pocoOneA : IMyInterfaceA
{     
   public IMyInterfaceB B { get; set; }  // fails, can I strongly type an interface?? 
} 

关于c# - 如何对已定义为接口(interface)的属性进行强类型化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7095733/

相关文章:

delphi - 如何在Delphi中支持接口(interface)定义中的类方法

c# - 为参与者 '{actorName}' 获取基于回合的并发锁在 {time} 后超时

c# - 为输入声明一个 Brushes 变量

c# - 将Kinect深度图像捕获到png文件

interface - 在 Go 中的结构中使用接口(interface)

java - 从java接口(interface)中的默认方法调用方法

java - 接口(interface)允许任何子类参数

c# - 事件报告 PDF 生成

C# : add Main methods in classes to quicktest

objective-c - 私有(private)接口(interface)与私有(private)方法 - objective-c