C#中具有显式接口的对象初始值设定项

时间:2010-04-05 11:42:54

标签: c# explicit-interface

如何在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" };

2 个答案:

答案 0 :(得分:4)

显式接口方法/属性是私有的(这就是为什么它们不能有访问修饰符:它总是private,因此会冗余*)。所以你不能从外面分配给他们。您不妨问:我如何从外部代码分配私有属性/字段?

(*虽然为什么他们没有与public static implicit operator做出同样的选择是另一个谜!)

答案 1 :(得分:3)

你做不到。访问显式实现的唯一方法是通过强制转换为接口。 ((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; }
}
相关问题