11

C#で明示的なインターフェイス実装を使用してオブジェクト初期化子を使用するにはどうすればよいですか?

public interface IType
{
  string Property1 { get; set; }
}

public class Type1 : IType
{
  string IType.Property1 { get; set; }
}

...

//doesn't work
var v = new Type1 { IType.Property1 = "myString" };
4

2 に答える 2

4

できません。明示的な実装にアクセスする唯一の方法は、インターフェイスへのキャストを使用することです。((IType)v).Property1 = "blah";

理論的には、プロパティをプロキシでラップしてから、初期化でプロキシ プロパティを使用できます。(プロキシはインターフェイスへのキャストを使用します。)

class Program
{
    static void Main()
    {
        Foo foo = new Foo() { ProxyBar = "Blah" };
    }
}

class Foo : IFoo
{
    string IFoo.Bar { get; set; }

    public string ProxyBar
    {
        set { (this as IFoo).Bar = value; }
    }
}

interface IFoo
{
    string Bar { get; set; }
}
于 2010-04-05T11:57:50.073 に答える
4

明示的なインターフェイス メソッド/プロパティはプライベートです (これが、アクセス修飾子を持つことができない理由です: 常にそうprivateであるため、冗長になります*)。したがって、外部から割り当てることはできません。外部コードからプライベート プロパティ/フィールドに割り当てるにはどうすればよいですか?

(※なぜ同じ選択をしなかったのかpublic static implicit operatorはまた謎ですが!)

于 2010-04-05T11:54:23.427 に答える