[英]Is there a way to initialize EII property within constructor?
Let's start with code from MS page:让我们从 MS 页面的代码开始:
interface ILeft
{
int P { get;}
}
interface IRight
{
int P();
}
class Middle : ILeft, IRight
{
public int P() { return 0; }
int ILeft.P { get { return 0; } }
}
I would like to change Middle
in such way, the EII property is once initialized, something like this:我想以这种方式更改
Middle
,EII 属性一旦初始化,如下所示:
class Middle : ILeft, IRight
{
public int P() { return 0; }
int ILeft.P { get; }
Middle()
{
ILeft.P = 0;
}
}
Above code does not compile, thus my question -- is there a syntax for doing this?上面的代码无法编译,因此我的问题是 - 是否有这样做的语法?
I am asking about syntax, because brute force way would be to declare private field and redirect ILeft.P
getter to return data from it.我问的是语法,因为蛮力方法是声明私有字段并重定向
ILeft.P
getter 以从中返回数据。
I think the only other possibility besides your suggested approach of using a backing field rather than an auto-property is to use the property initializer syntax, eg:我认为除了您建议的使用支持字段而不是自动属性的方法之外,唯一的另一种可能性是使用属性初始值设定项语法,例如:
int ILeft.P { get; } = 0;
Of course with this you can't initialize based on, say, an argument passed to the constructor, so it provides only limited additional flexibility.当然,你不能根据传递给构造函数的参数进行初始化,因此它只能提供有限的额外灵活性。
(There is a proposal to add " primary constructors " to the C# language, which might make it possible to initialize a get-only explicitly implemented interface property based on a constructor argument, though as far as I know there's no timeline for its inclusion in the language so I wouldn't hold your breath...) (有一个建议将“ 主构造函数”添加到 C# 语言中,这可能使基于构造函数参数初始化仅获取显式实现的接口属性成为可能,但据我所知,没有时间表将其包含在语言,所以我不会屏住你的呼吸......)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.