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

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

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

于 2010-04-05T11:54:23.427 回答
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 回答