C# 中具有显式接口的对象初始值设定项
如何在 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" };
How can I use an object initializer with an explicit interface implementation in 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" };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。访问显式实现的唯一方法是通过对接口的强制转换。
((IType)v).Property1 = "blah";
理论上,您可以在属性周围包装一个代理,然后在初始化中使用代理属性。 (代理使用接口的强制转换。)
You can't. The only way to access an explicit implementation is through a cast to the interface.
((IType)v).Property1 = "blah";
You could theoretically wrap a proxy around the property, and then use the proxy property in initialization. (The proxy uses the cast to the interface.)
显式接口方法/属性是私有的(这就是为什么它们不能具有访问修饰符:它始终是
私有
,因此是多余的*)。所以你不能从外部分配给他们。您可能还会问:如何从外部代码分配给私有属性/字段?(*尽管为什么他们没有对公共静态隐式运算符做出相同的选择是另一个谜!)
Explicit interface methods/properties are private (this is why they cannot have an access modifier: it would always be
private
and so would be redundant*). So you can't assign to them from outside. You might as well ask: how can I assign to private properties/fields from external code?(* Though why they didn't make the same choice with
public static implicit operator
is another mystery!)