@adrianbanksの答えは私の改善かもしれないと思いましたが、実際には(気の利いたにもかかわらず)そうではないと思います-渡されるパブリックインターフェイスインスタンスが内部インスタンスも実装するという保証がないため-これこのソリューションにも当てはまります。また、実装型が次の場合にのみ機能するということもありますinternal
。これは、パブリック型を標準インターフェイスの実装として、または階層のベースとして提供する場合には適していません。
これは私が使用するものです。与えられた:
interface myInterface
{
string myProperty { get; set; }
}
public interface myPublicInterface
{
string myProperty { get; }
}
まず、コンパイラが一貫性のないアクセシビリティについてうめき声を上げるため、継承を行うことはできません。したがって、プロパティバッカーを使用して内部のものを明示的に実装し、次にパブリックのものを暗黙的に実装できます。myPublicInterface
myInterface
public class MyClass : myInterface, myPublicInterface
{
private string _myProperty;
string myInterface.myProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
public string myProperty
{
get { return _myProperty; }
}
}
注 - 場合によっては、getter はプライベート バッカーには適していない可能性がありますが、他のプロパティから値を計算するロジックである可能性があります。その場合-DRYに保つために-ロジックをパブリックゲッターに入れ、それを明示的なゲッターにリーチすることができます:
string myInterface.myProperty
{
get { return MyProperty; }
set { /*whatever logic you need to set the value*/ }
}
public string myProperty
{
get { /*whatever complex logic is used to get the value*/ }
}
逆の方法で行うこともできますが、内部インターフェイスへの見栄えの悪いインライン キャストを行う必要があります。
string myInterface.myProperty
{
get { /*whatever complex logic is used to get the value*/ }
set { /*whatever logic you need to set the value*/ }
}
public string myProperty
{
get { return ((myInterface)this).myProperty; }
}
可能な限り避けてください。