我正在尝试对已定义为接口(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/